In .Net, all data types have a fixed range and can be represented in System namespace. For example System.Boolean type can be assigned from {true, false} values. You can not assign null to any value type data type (int, boolean,..) because it will create empty object reference. But you can assign null value to reference type, for example string type.
//it will produce compile time error
int i =null;
boolean bool = null;
//it is fine, because string is a reference type
string str = null;
But, there are some situations where you need assign null to value types. For example you are calling data base and assigning table columns to some variables, data base table might have null values. In this type of situation you can assign null value to value type variables using question mark symbol(?). Just suffix the question mark symbol(?) before the underlying nullable data type. You cannot suffix question mark symbol(?) for the reference type(ex: string), issued with a compile time error.
//define some nullable value types
int? i = null;
int? i = 10;
boolean? bool = true;
boolean? bool = null;
//it produces compile time error
String? str = “This is reference type”;
Now we will take small example which calls the data base and assign data base columns to some nullable local variables as shown below.
class Program
{
static void Main(string[] args)
{
int? i;
Emp objEmp=new Emp();
i = objEmp.GetIdFromDB();
if (i.HasValue)
{
Console.WriteLine("i = {0}", i);
}
else
{
Console.WriteLine("id is undefined");
}
Console.ReadLine();
}
}
class Emp
{
public int? GetIdFromDB()
{
//call database and return int value. Here I am returning null value
return null;
}
}
Here GetIdFromDB() calls the database and returns some int type value which may be null. We are assigning this value to some local nullable variable.
jQuery15209376147449313279_1322621273476
Sometimes, you want to replace null value with some other value. For example you are calling data base and you want to assign some default value to local variables if the data base value is null. In this case you can use jQuery152009614988238244349_1326354838557 operator. If we take same above example, if GetIdFromDB() method returns null value, we may need to assign some default value to local variable instead of null. We can do it as shown below.
class Program
{
static void Main(string[] args)
{
int? i;
Emp objEmp=new Emp();
i = objEmp.GetIdFromDB() ?? 100;
if (i.HasValue)
{
Console.WriteLine("i = {0}", i);
}
else
{
Console.WriteLine("id is undefined");
}
Console.ReadLine();
}
}
class Emp
{
public int? GetIdFromDB()
{
//call database and return int value. Here I am returning null value
return null;
}
}
In the above, we are assigning 100 to local int variable “i” if GetIdFromDB() method returns null value by using ?? operator.