Again, I really hope this is not a matter of opinion; I am trying to find out which one is best to determine the type of object belonging to a particular hierarchy in C #. I have two ways to develop my application:
1 - Use the property in the base class:
public abstract class Parent
{
public abstract TypeOfObject TypeOfObject { get; }
}
public class Child1 : Parent
{
public override TypeOfObject TypeOfObject { get { return TypeOfObject.Child1 } }
}
public class Child2 : Parent
{
public override TypeOfObject TypeOfObject { get { return TypeOfObject.Child2 } }
}
public enum TypeOfObject
{
Child1,
Child2
}
public static void Main()
{
Parent p = new Child1();
switch (p.TypeOfObject)
{
case TypeOfObject.Child1: _doSomethingWithChild1(p);break;
case TypeOfObject.Child2: _doSomethingWithChild2(p);break;
}
}
2 - use the is operator
public abstract class Parent
{
}
public class Child1
{
}
public class Child2 : Parent
{
}
public enum TypeOfObject
{
Child1,
Child2
}
public static void Main()
{
Parent p = new Child1();
if (p is Child1) _doSomethingWithChild1(p);
if (p is Child2) _doSomethingWithChild2(p);
}
What are the implications of each alternative? I think 2 has a higher performance rating because it relies on metadata, but 1 seems less elegant. Also, I learned how to do this 1 way in C ++ ... I'm not sure if this needs to be done with C #.
EDIT 1:
I have added an override keyword to the code above.
EDIT 2:
Sorry, I probably haven’t clarified the situation. I will illustrate this better:
, WPF Panel, Children, UIElement s. , ... , , . , , , ? , ?