Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare types

Tags:

c#

.net

Quick question: how to compare a Type type (pun not intended) with another type in C#? I mean, I've a Type typeField and I want to know if it is System.String, System.DateTime, etc., but typeField.Equals(System.String) doesn't work.

Any clue?

like image 234
Archedius Avatar asked Mar 30 '11 06:03

Archedius


People also ask

How to compare types C#?

The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

How do you compare two types in Python?

== and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity. Let's look at the code.

How do you compare data types in Java?

To compare object types we need to implement the interface java. lang. Comparable<T> with its single method int compareTo(T) . The result represents the natural order of our type, not just arithmetical comparability.

Can we compare types in Python?

Use type() to compare types Call type(obj) to return the type of obj . Use == to compare this type with another.

How to compare object type with class in C#?

Equals() Method. Type. Equals() Method is used to check whether the underlying system type of the current Type is the same as the underlying system type of the specified Object or Type.

How do you compare data types of variables in Python?

Python has a built-in function called instance() that compares the value with the type given. It the value and type given matches it will return true otherwise false. Using isinstance(), you can test for string, float, int, list, tuple, dict, set, class, etc.


1 Answers

Try the following

typeField == typeof(string) typeField == typeof(DateTime) 

The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.

like image 64
JaredPar Avatar answered Sep 21 '22 15:09

JaredPar