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
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.