2016年8月31日 星期三

[C#] Initialize var with null (Set var to null)


筆記一下var 需要初始化為 null 的寫法。
var result = (dynamic)null;

其他作法:


//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; 

Reference: http://www.itorian.com/2015/04/initialize-var-with-null-or-empty-in-c.html

沒有留言:

張貼留言