Hello all,
Again, I really hope this isn't a matter of opinion; I'm trying to know which is the best way to determine the type of an object that belongs to a certain hierarchy in C#. I have two ways to design my application:
1 - Use a property on 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 greater performance hit since it relies on metadata, but 1 seems way less elegant. Besides, I learned to do this the 1 way in C++... I'm not sure it's necessary to do so with C#.
EDIT 1:
I've added the override keyword to the code above.
EDIT 2:
I'm sorry, I've probably not made myself clear. I will illustrate it better:
For example, I have a WPF Panel
object that has a Children
property, which returns me UIElement
s. I need to know what type a certain element is to act upon it... in my particular case, the user is drawing a graph on the screen, so I need to know how many nodes and how many connections are drawn in order to store then at the database. I can't, unfortunately, use polymorphism for that, right? How will I know if I should add a line to my nodes table or to my connections table?