Search code examples
c#nullnullablevar

Why can C# check if a 'var' is null?


I have the following code:

List<IMessage> messageList = new List<IMessage>();

foreach(var msg in messageList)
{
    if(msg != null)
    {

    }
}

How is it possible to check the var msg against null? What tells the compiler that var is an IMessage and not an int or some other type that isn't nullable?

If you look at the example over at MSDN they give the implicitly typed variables initial values (whereby the declaration becomes explicit). In my case I do not even give it a value, yet the compiler has no problem with it. How does the compiler know that the msg is nullable?


Solution

  • The compiler knows that msg is nullable because it is statically typed. The static type is IMessage, even though you did not name it.

    The reason the compiler substituted IMessage for var is that it appeared in foreach (var identifier in collection ) and the collection is an expression of a type that implements IEnumerable<IMessage>.

    Every appearance of var will have some type substituted statically. (It's possible for that to be dynamic, but dynamic is not a default, it can only apply when it can be inferred under the static type inference rules) If the static type inference rules can't find a unique type to substitute, then that use of var is disallowed.