Object Type Definition

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. , ... , , . , , , ? , ?

+3
3

( - ), , .

++ ++

# 1 # 2. . 1 , 2 , CLR. CLR, , , , ,

- , , - . ,

0

. - ( / , )? , doSomething(), , , _doSomethingWithChild1, Child1.doSomething .. , OO all - , , - ! ++ , ++ virtual. / , ( , ifs) , , ( JIT , ), "WTF" stare;)

+10

The first option is optional. if you look at Object (the base for ALL objects in C #), you will find a member GetType().

In our production code, we often use method 2, mainly for "down-casting", which distinguishes my base class from a class that is derived from the specified base class ...

if ( myObject is Type1 ) dosomething();
if ( myObject is Type2 ) dosomethingelse();

we also use the operator as....

Type1 object1 = someotherobject as type1;
if ( object1 != null ) dosomething();

The nice thing about this is that you will not get such exceptions as if you tried something like this:

((TypeFoo)object1).bar(); // if object 1 is NOT of TypeFoo you get an exception
+4
source

Source: https://habr.com/ru/post/1769615/


All Articles