Null Reference Sorts in C#
Null reference varieties are varieties in C# that may have a worth of null, which signifies that the variable doesn’t reference any object in reminiscence. Null reference varieties are continuously used to verify whether or not an object exists or not, and to deal with surprising exceptions that will happen, for example, take into account the next code:
namespace NullReferenceTypesExample
{
class Program
{
static void Principal(string[] args)
{
string identify = null;
if (identify == null)
{
Console.WriteLine(“Identify isn’t assigned”);
}
}
}
}
First the string variable identify is asserted and assigned a worth of null. The if-statement is used to verify if the identify variable is null or not, if the identify variable is null, then the console outputs the message “Identify isn’t assigned”.
A nullable worth sort is a worth sort that may also be assigned a worth of null, that is helpful when coping with worth varieties, which can not have null values by default, right here is one other instance:
namespace NullReferenceTypesExample
{
class Program
{
static void Principal(string[] args)
{
int? num = null;
if (num.HasValue)
{
int worth = num.Worth;
Console.WriteLine(“The worth of num is: “ + worth);
}
else
{
Console.WriteLine(“The worth of num is null”);
}
Console.ReadKey();
}
}
}
First the nullable integer variable num is asserted and assigned a worth of null, then the if assertion is used to verify if num has a worth or not. If num does have a worth, then the integer worth is assigned the worth of num:
Conclusion
Null reference sort is a vital characteristic of C# programming that permits builders to put in writing extra environment friendly and sturdy code. Through the use of null reference varieties, you’ll be able to deal with null values and uninitialized variables with ease and keep away from surprising exceptions that may trigger your code to fail. On this article, we have now explored what null reference varieties are in C# and supplied examples of their utilization.