Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermining a Type of an Object
    primarykey
    data
    text
    <p>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:</p> <p><strong>1 - Use a property on the base class:</strong></p> <pre><code>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; } } </code></pre> <p><strong>2 - Use the is operator</strong></p> <pre><code>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); } </code></pre> <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#.</p> <p><strong>EDIT 1:</strong></p> <p>I've added the <em>override</em> keyword to the code above. </p> <p><strong>EDIT 2:</strong></p> <p>I'm sorry, I've probably not made myself clear. I will illustrate it better: </p> <p><strong>For example</strong>, I have a WPF <code>Panel</code> object that has a <code>Children</code> property, which returns me <code>UIElement</code>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload