Reputation: 54521
I would like to make assertions similar to the following:
aMethod.ReturnType == double
aString.GetType() == string
The above example clearly doesn't compile because double
and string
are not objects of type Type
, they're not even legal C# expressions.
How do I express a Type
of a certain C# type?
Upvotes: 2
Views: 97
Reputation: 4376
Use typeof to get and compare types.
aMethod.ReturnType == typeof(double)
aString.GetType() == typeof(string)
Upvotes: 6
Reputation: 223207
use is operator
Checks if an object is compatible with a given type.
bool result1 = aMethod.ReturnType is double;
bool result2 = aString is string;
Consider the following examples:
bool result1 = "test" is string;//returns true;
bool result2 = 2 is double; //returns false
bool result3 = 2d is double; // returns true;
EDIT: I missed that aMethod.ReturnType
is a type not a value, so you are better of checking it using typeof
bool result1 = typeof(aMethod.ReturnType) == double;
Consider the following example.
object d = 10d;
bool result4 = d.GetType() == typeof(double);// returns true
Upvotes: 2
Reputation: 2996
As other people said, use typeof(YourType)
, or the is
operator (be carefull, is
isn't a strict operator (think about inheritance) : for example, MyClass is object
is true !)..
I don't know why you need aMethod.ReturnType
, but it seems that you need generic parameters. Give it a try !
Upvotes: 0