Vencovsky
Vencovsky

Reputation: 31605

Can c# know the type of an object when it's value is null?

While making some validation, I can across this situation

public override bool IsValid(object value)
{
    if(!(value is IFileUploadInfo) && !(value is IEnumerable<IFileUploadInfo>))
        throw new ArgumentException($"Cannot use {nameof(FileValidationAttribute)} in a property that isn't of type {nameof(IFileUploadInfo)} or {nameof(IEnumerable<IFileUploadInfo>)}");

    // rest ...
}

Where I need to test if a object is of the type that I want, but if value is null, will c# know the type of that object even when it's null?

Upvotes: 2

Views: 130

Answers (2)

Guru Stron
Guru Stron

Reputation: 141990

No, you can't obtain type information from null with type check.

MyClass mc = null;
object obj = mc;
Console.WriteLine(obj is MyClass); // prints "False"

Docs are clear about it:

The is expression is true if expr isn't null, and ...

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190945

You can't. Passing with object in erases what the type was at compile time. Hence you have to do some pattern matching or casting to get it back out. Hence, null doesn't carry any type information with it.

You could make the method generic and then you could get what the type was.

public override bool IsValid<T>(T value)
{
    Type t = typeof(T);
    ... 
    // rest of code
}

Upvotes: 2

Related Questions