How can I find out what data type some variable is holding? (e.g. int, string, char, etc.)
I have something like this now:
using System;
using System
Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:
If you know the type you want to compare it with, use the is
or as
operators:
if( unknownObject is TypeIKnow ) { // run code here
The as
operator performs a cast that returns null if it fails rather than an exception:
TypeIKnow typed = unknownObject as TypeIKnow;
If you don't know the type and just want runtime type information, use the .GetType() method:
Type typeInformation = unknownObject.GetType();
In newer versions of C#, you can use the is
operator to declare a variable without needing to use as
:
if( unknownObject is TypeIKnow knownObject ) {
knownObject.SomeMember();
}
Previously you would have to do this:
TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
knownObject.SomeMember();
}
Its Very simple
variable.GetType().Name
it will return your datatype of your variable