hhkbbb
hhkbbb

Reputation: 79

Why are these not the same? And why isn't `type.GetType() is Test` true in C#?

public class Test { }
public class InheritTest : Test { }

private void Main(string[] args)
{
   var test        = new Test();
   var inheritTest = new InheritTest();

   Console.WriteLine($"{test.GetType() is Test}");               // False
   Console.WriteLine($"{inheritTest.GetType() is InheritTest}"); // False
}

GetType is the actual instance. But why isn't type.GetType() is Test true?

Upvotes: 0

Views: 74

Answers (1)

TheGeneral
TheGeneral

Reputation: 81593

is (C# Reference)

The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type.

Object.GetType Method ()

Gets the Type of the current instance.

Basically you don't need GetType()

Update

type.GetType() returns a System.Type

So along the lines of your original intentions you can imagine the following

// as you see, GetType() returns a type
Console.WriteLine($"{type.GetType() is Type}"); // True

typeof returns a Type as well , so the following can be used to compare as well

Used to obtain the System.Type object for a type

Console.WriteLine($"{type.GetType() == typeof(Test)}"); // True

Upvotes: 4

Related Questions