Ashwani 的个人资料Ashwani Roy's BI Blog照片日志列表更多 ![]() | 帮助 |
|
|
11月17日 NULLABLE TYPES. How and When to useWe , who deal with database , always complained how we cannot assign NULL to a value type variable in C#. Somewhere in Microsoft Labs someone heard out prayers and C# 2.0 came up with system.Nullable<T>. A way in which we can assign NULL to C# variable and then check if the variable HasValue or not and if it does than what is the Value. Here is a small C# 2.0 console application that shows how to declare and varibale as NULLBALE and use functions "HasValue" and "value"
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace PracticeSamples { class Program { static void Main(string[] args) { /// /// system.Nullable <T> helps a value type being used a reference type ///
//int i = null; //This will throw an error here. So what if I want to assign NULL to some var Nullable <int> j = null;//Does not throw Error Console.WriteLine("Value of J ="+j);
/// /// declaring a varibale a Nullable swithes on Hasvalue and Value function /// Nullable<bool> k = null;//Does not throw Error k = true; if (k.HasValue)//You can do this to check if the variable has been assigned or not { Console.WriteLine("Value of K =" + k.Value); } else { Console.WriteLine("K has not been assigned any value and is NULL");
}
} } } Output is : = Value of K = True Now we understand what a NULLABLE type is and how to declare a value type variable as NULLABLE and how to use HasValue and Value function of a NULLABLE type variable .
Hope this helps someone |
|
|