Nullable in c#
Nullable types can represent all the values of an underlying type, and an additional null value. Nullable types are declared in one of two ways:
System.Nullable variable
-or-
T? variable
Any value type may be used as the basis for a nullable type
class Program
{
static void Main(string[] args)
{
int? x = 10;
if (x.HasValue)
{
System.Console.WriteLine(x.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
Console.ReadKey();
int? y = null;
if (y != null)
{
System.Console.WriteLine(y.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
Console.ReadKey();
int? n = 5;
//int m1 = n; // Will not compile.
int m2 = (int)n; // Compiles, but will create an exception if n is null.
int m3 = n.Value; // Compiles, but will create an exception if n is null.
Console.ReadKey();
int A = 0;
System.Console.WriteLine("A++ = {0}", A++);
A = A + 1;
System.Console.WriteLine("A = A + 1 {0}", A);
System.Console.WriteLine("++A {0}", ++A);
Console.ReadKey();
}
}
System.Nullable
-or-
T? variable
Any value type may be used as the basis for a nullable type
class Program
{
static void Main(string[] args)
{
int? x = 10;
if (x.HasValue)
{
System.Console.WriteLine(x.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
Console.ReadKey();
int? y = null;
if (y != null)
{
System.Console.WriteLine(y.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
Console.ReadKey();
int? n = 5;
//int m1 = n; // Will not compile.
int m2 = (int)n; // Compiles, but will create an exception if n is null.
int m3 = n.Value; // Compiles, but will create an exception if n is null.
Console.ReadKey();
int A = 0;
System.Console.WriteLine("A++ = {0}", A++);
A = A + 1;
System.Console.WriteLine("A = A + 1 {0}", A);
System.Console.WriteLine("++A {0}", ++A);
Console.ReadKey();
}
}
Comments
Post a Comment