Surprisingly the following code fails the Assert:
int? wtf = 0;
Assert.IsType<Nullable<int>>(wtf);
So just out curiosity, how can you determine if a given instance is a Nullable<> object or not?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well firstly,
Nullable<T>is a struct, so there isn’t an object as such. You can’t callGetType(), as that will box the value (at which point you either get null and thus an exception, or a boxed non-nullable value and therefore not the type you want).(Boxing is what’s messing up your assertion here – I would assume that
IsTypeacceptsobject.)You can use type inference though to get the type of the variable as a type parameter:
That’s not a huge amount of use when you know the exact type at compile-time as in your example, but it’s useful for generics. (There are alternative ways of implementing it, of course.)
What’s your real life situation? I assume it’s not an assertion like this, given that you know the answer to this one at compile time.