开发者

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

开发者 https://www.devze.com 2023-03-27 14:55 出处:网络
This question already has answers here: Most efficient way to check if an object is a value type (6 answers)
This question already has answers here: Most efficient way to check if an object is a value type (6 answers) 开发者_运维问答 Closed 9 years ago.

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消