Search code examples
c#.netderived-class

Better way to get property from derived class


i have next class

public class MainClass
{
   public ClassA someProp { get; set; }
}

public class ClassA
{
   public virtual Type Types => Type.None;
}

public class ClassB:ClassA
{
   public override Type Types => Type.Default;
        
   public string FieldName { get; set; }
}

i want get FieldName from ClassB

var result = entities.Where(x => x.someProp != null).Select(x => x.someProp).ToList();

and than i get

var fields = (from ClassB in result select t.FieldName).ToList();

what is better way get FieldName from ClassB

I don't think this is the best solution. Maybe there are some best practices for my question?


Solution

  • You've to filter the entities and get only those that are ClassB, then read the property as usual.

    var values = entities
          .Select(mainClass => mainClass.SomeProp)
          .OfType<ClassB>()
          .Select(classB => classB.FieldName)