Home  >  Article  >  Backend Development  >  C# Nullable String

C# Nullable String

WBOY
WBOYOriginal
2024-09-03 15:22:04634browse

In C#, two types of variables exist value types and reference types. Value type variables cannot be assigned null, whereas we can assign null to reference type variables. As the string is a reference type, it can be null. In this topic, we are going to learn about C# Nullable String.

To assign null to a value type, we need to use Nullable struct. The nullable type can only be used with value types, not reference types. So, we cannot use nullable with string. We can store a nullable instead of a reference type to hold a null value.

Syntax with Explanation

The syntax to assign null to a string variable is as follows:

string str = null;

Here, str is a variable of type string, and ‘null’ is the keyword used to specify the null value. In the above statement, we directly assign null to string because it is a reference type and can hold a null value.

Nullable struct will assign null to a value type. Its syntax is as follows:

Nullable<dataType> variableName = null;

Another way of using the Nullable type is as follows:

dataType? variableName = null;

The dataType is the above two statements is any value type data type, and variableName is the user-defined name given to the variable.

How to work with Nullable type and null string in C#?

Nullable type in C# assigns null values to value type variables like type int, float, bool, etc., because they cannot store null values. On the other hand, we cannot use nullable with string or any other reference type variable because it can directly store a null value.

A nullable type is nothing but an instance of a struct System.Nullable where T represents a value type of data type. For example, in nullable type float, we can store ‘true,’ ‘false,’ and ‘null.’ We can understand this with the statements given below:

//below statement is valid because we can store null in nullable of bool

Nullable<bool> boolVal = null;

//below statement is not valid because we cannot store null in a variable of type bool

bool boolVal = null;

When we use the above statement, we will get an error saying, ‘Cannot convert null to bool because it is a non-nullable value type.’

Another way to create a nullable type is by using the ‘?’ operator, as shown below:

bool? boolVal = null;

Now, to access the value of a nullable type, we need to use GetValueOrDefault() method. With the help of this method, we will get the original assigned value if the value is not null. On the other hand, if the value is null, we will get the default value of zero.

Apart from this, we can use Nullable.HasValue to check whether the object has been assigned a value or not. If the object has been assigned a value, it will return true if the object does not contain any value.

We cannot use the nullable type with ‘var,’ and we cannot have the nested nullable type; it will give us a compile-time error.

Now, let us talk about the null string in C#. We can directly assign null to a string in C# and assign a string with ‘string. Empty’ read-only field, which represents that the string is empty.

We cannot call any methods on the null string and cannot use any string properties on the null string, whereas we can do the same with empty strings. For example, if we will check the length of an empty string using a string. Length property, then we will get the result as zero, whereas if we check the length of a null string, then we will get a runtime exception saying ‘System.NullReferenceException: Object reference not set to an instance of an object. We will get the same exception when we try to call any string method on a null string. This is because a null string is not an instance of a System. String. We can understand this with the help of the following statements:

Example for empty string:

string str = string.Empty;
int a = str.Length; //the result of this statement will be zero

Example for null string:

string str = null;
int a = str.Length; //this statement will give NullReferenceException

Examples of C# Nullable String

Different examples are mentioned below:

Example #1

Example showing how to create a nullable type.

Code:

using System;
namespace ConsoleApp4
{
public class Program
{
public static void Main()
{
try
{
//defining nullable type for int
Nullable<int> intVal1 = null;
int result1;
Nullable<int> intVal2 = 53;
int result2;
//using GetValueOrDefault()
//to get value from nullable type
result1 = intVal1.GetValueOrDefault();
result2 = intVal2.GetValueOrDefault();
Console.WriteLine("Integer having null: {0}", result1);
Console.WriteLine("Integer having value: {0}", result2);
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadLine();
}
Console.ReadLine();
}
}
}

Output:

C# Nullable String

Examples #2

For example, it creates a nullable type using the ‘?’ operator and checks whether it contains a value or not using HasValue.

Code:

using System;
public class Program
{
public static void Main()
{
try
{
//defining nullable type
//using '?' operator
int? intVal1 = null;
bool result1;
int? intVal2 = 53;
bool result2;
//using HasValue to check
// if the object has been assigned a value or not
result1 = intVal1.HasValue;
result2 = intVal2.HasValue;
Console.WriteLine("Integer having null: {0}", result1);
Console.WriteLine("Integer having value: {0}", result2);
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadLine();
}
Console.ReadLine();
}
}

Output:

C# Nullable String

Example #3

Example to check whether a string is null, empty, or contains a value using IsNullOrEmpty() method.

Code:

using System;
public class Program
{
public static void Main()
{
string str1 = null;
string str2 = string.Empty;
string str3 = "Learning C#";
Console.WriteLine("str1 is null or empty: {0}", string.IsNullOrEmpty(str1));
Console.WriteLine("str2 is null or empty: {0}", string.IsNullOrEmpty(str2));
Console.WriteLine("str3 is null or empty: {0}", string.IsNullOrEmpty(str3));
Console.ReadLine();
}
}

Output:

C# Nullable String

Conclusion

In C#, the value type variables like variables of type int, float, bool, double, etc., cannot store null value, whereas the reference type variables like string can store null value. To store null value in value type variables, we can use Nullable struct.

The above is the detailed content of C# Nullable String. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# Memory LeakNext article:C# Memory Leak