Answers for "list of 2 different inherent classes c#"

C#
0

list of 2 different inherent classes c#

// a Pseudo-example using interfaces. <--- Worked great for me!

public interface IPrinter
{
   void Send();
   string Name { get; }
}

public class PrinterType1 : IPrinter
{
  public void Send() { /* send logic here */ }
  public string Name { get { return "PrinterType1"; } }
}

public class PrinterType2 : IPrinter
{
  public void Send() { /* send logic here */ }
  public string Name { get { return "Printertype2"; } }

  public string IP { get { return "10.1.1.1"; } }
}


// ...
// then to use it
var printers = new List<IPrinter>();

printers.Add(new PrinterType1());
printers.Add(new PrinterType2());

foreach(var p in printers)
{
  p.Send();

  var p2 = p as PrinterType2;

  if(p2 != null) // it's a PrinterType2... cast succeeded
    Console.WriteLine(p2.IP);
}
Posted by: Guest on August-23-2020
0

List of 2 different iherent classes c#'

List<BaseA> list = ...

  var result = list
    .OfType<AA>() // Filter out AA instances only
    .ElementAt(0) // or just First();
    .AID;
Posted by: Guest on August-23-2020

C# Answers by Framework

Browse Popular Code Answers by Language