How to check a hold Instance or Type variable in C #

I have a class Test

public class Test { }

      

Now I have a variable object1

that contains an instance Test

.

object object2 = new Test();

// some code

object2 = typeof(Test);

      

object2

will take both a type and an instance of the class Test

in different scenarios. How can I check what value it has. i.e. instance Test

or typeTest

+3


source to share


5 answers


if (object2 is Test) { ... }
if (object2 is Type) { ... }

      



But don't do this.

+5


source


Without testing it, you can check

if (object2 is Test) // .. we have an instance of Test
else if (object2 == typeof(Test)) // we have the second case

      



Btw: this is bad design. I believe the variable should be introduced for a specific purpose.

+1


source


if (object2 is Type) {...}

// when object2 is of type Type

if (object2 is Test) {...}

// when object2 is of type Test

.. hence has an instance

+1


source


var object2Type = object2 as Type;
if (object2Type != null)
{
    // Do something
}
else
{
    var object2Test = (Test)object2;
    // Do something else
}

      

+1


source


You can also use my library ( link ):

object2.DetermineType()
       .When((Test target) => { /* action to do */ })
       .When((Type target) => { /* action to do */ })
       .Resolve();

      

or

object2.DetermineType()
       .When<Test>(target => { /* action to do */ })
       .When<Type>(target => { /* action to do */ })
       .Resolve();

      

But if you need to define the type this way, your design may not be very good.

+1


source







All Articles