How should you test if a variable is a value type in C#? [duplicate]
I have a few places where I have a generic type parameter that is not limited to class (or struct), and when I try to compare variables of that type against null
, Resharper underlines it, complaining that I may be comparing a value type to null
(a valid objection, to be sure). Is there an accepted way of checking if a variable is a value type before comparing against null?
For example:
public TObject MyProperty { get; set; }
...
private void SomeMethod()
{
if(MyProperty == null) //Warning here
{
...
}
}
I've been doing if(!(MyProperty is ValueType) && MyProperty)
--is that valid? It doesn't get rid of the warning, but that doesn't necessarily mean anything.
What do you want to do in the case that it is a value type? sometimes I will do:
public void DoStuff<T> (T variable)
{
if(variable == default(T))
... // true if null or 0 in the case of a value type
}
Or:
if( typeof(T).IsValueType )
See here.
You can use reflection, but it's slow and should be avoided:
bool isValueType = typeof(TObject).IsValueType;
Does your generic method really have a need to pass both reference and value types as its type parameter?
You could just compare the type:
if (MyProperty.GetType() == typeof(...))
{
}
You are getting a warning because MyProperty
isn't assigned to.
public static bool IsNull<T>(T t)
{
return ((Object)t == null);
}
精彩评论