What's the exact difference between the two?
// When calling this method with GetByType<MyClass>() public bool GetByType<T>() { // this returns true: return typeof(T).Equals(typeof(MyClass)); // this returns false: return typeof(T) is MyClass; }
The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType . If you don't have an instance, but you know the type name (and just need the actual System. Type to inspect or compare to), you would use typeof .
The C# typeof operator ( GetType operator in Visual Basic) is used to get a Type object representing String. From this Type object, the GetMethod method is used to get a MethodInfo representing the String. Substring overload that takes a starting location and a length.
You should use is AClass
on instances and not to compare types:
var myInstance = new AClass(); var isit = myInstance is AClass; //true
is
works also with base-classes and interfaces:
MemoryStream stream = new MemoryStream(); bool isStream = stream is Stream; //true bool isIDispo = stream is IDisposable; //true
The is
keyword checks if an object is of a certain type. typeof(T)
is of type Type
, and not of type AClass
.
Check the MSDN for the is keyword and the typeof keyword
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With