Initialize var with null or empty in C# - learn workarounds

In this quick code you will learn how to initialize var so that it works like null or empty. Technically, this is not possible.

Why?

C# is a strictly/strongly typed language. var was introduced for compile-time type-binding for anonymous types yet we can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.

When we say, var y = null; the compiler cannot resolve this because there's no type bound to null. You can make it like this.

string y = null;
var x = y;

This will work because now x can know its type at compile time that is string in this case.

What are alternatives?

So your options are:


//initializes to non-null; cannot be reassigned a value of any type; I prefer this
var x = new { };

//initializes to non-null; can be reassigned a value of any type
var x = new object();

//initializes to null; dangerous and finds least use; can be reassigned a value of any type
dynamic x = null;
var x = (dynamic)null;

//initializes to null; more conventional; can be reassigned a value of any type
object x = null;

//initializes to null; cannot be reassigned a value of any type
var x = (T)null;



Hope this helps.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System