I've seen both done in some code I'm maintaining, but don't know the difference. Is there one?
let me add that myCustomer is an instance of Customer
The gettype() function returns the type of a variable.
GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.
The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.
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.
The result of both are exactly the same in your case. It will be your custom type that derives from System.Type
. 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
.
EDIT: Let me add that the call to GetType
gets resolved at runtime, while typeof
is resolved at compile time.
GetType() is used to find the actual type of a object reference at run-time. This can be different from the type of the variable that references the object, because of inheritance. typeof() creates a Type literal that is of the exact type specified and is determined at compile-time.
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