Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should you test if a variable is a value type in C#? [duplicate]

Tags:

c#

.net

generics

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.

like image 667
Turner Hayes Avatar asked Dec 28 '22 15:12

Turner Hayes


2 Answers

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.

like image 122
CodingWithSpike Avatar answered Dec 30 '22 10:12

CodingWithSpike


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?

like image 45
BrokenGlass Avatar answered Dec 30 '22 09:12

BrokenGlass