Robokitty Robokitty - 2 months ago 4
C# Question

Compare a data type using a string or other format

I'd like to set a data type without having to create an extra variable in C#. Rather than creating an empty variable and then comparing a type.

CustomType empty; //empty variable
CustomType RealFooBar = new CustomType("extremeFoobar", false) //custom datatype with data in it

if(RealFooBar.GetType() == empty.GetType())

I would rather do it like this:

CustomType RealFooBar // already has data

if(RealFooBar.GetType() == {CustomType})

Is there a way to do this?

I tried
one time but it didn't seem to work that way. Or I didn't do it right.


You should use typeof if you know the type beforehand and use GetType only when you don't know and it will change during run time.

Another thing, if you only need to compare you can is keyword, ref: IS keyword

Any of these should work:

if(RealFooBar is string)
if(RealFooBar.GetType() == typeof(string))