What are Nullable types in C#?
What are Nullable types in C#?
Nullable types in C# allow you to assign null values to value types, which normally cannot be assigned null. This is useful when you need to represent the absence of a value for a value type, such as an integer, a boolean, or a struct.
In C#, you can declare a nullable type by appending a question mark (?) to the type name. For example:
int? age = null;
bool? isStudent = null;
Here are some key points about nullable types in C#:
To access the value of a nullable type, you can use the Value
property. However, if the nullable type is null, accessing the Value
property will throw a NullReferenceException
. To avoid this, you can use the null-conditional operator (?.
) or the null-coalescing operator (??
).
int? age = 25;
int ageValue = age.Value; // 25
age = null;
int defaultAge = age?.Value ?? 30; // 30
C# provides several operators that work with nullable types:
Null-conditional operator (?.
): This operator checks if the operand on the left is null before accessing its members. If the operand is null, it returns null; otherwise, it returns the result of the member access.
**Null-coalescing operato...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào