mabstrei
mabstrei

Reputation: 1220

Compare two Types

I've got a class looks quite like this:

object value;
Type type;

When I create the object I set the type to the type of the Object.

How can I compare this type with another type?

If for example the type is String:

type.Equals(String)

and

type == String 

does not work.

Upvotes: 11

Views: 24110

Answers (5)

Brain2000
Brain2000

Reputation: 4894

Type.Equals() requires that you also pass a Type. Thus, turn the string into a type:

type.Equals(GetType(string))

Upvotes: 0

Amirali Eshghi
Amirali Eshghi

Reputation: 1011

if(typeitem is string)
{
   // Your Code
}

Upvotes: 1

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55479

Check this might help you. Using Object.GetType()

http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx

Upvotes: 2

Peter
Peter

Reputation: 38455

well this should work

bool isSameType = (value != null && value.GetType() == type);

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126794

In this context, you compare your Type instance with the result of typeof(T), where T is the type you want to compare.

bool objectIsString = myType == typeof(string);

Upvotes: 15

Related Questions