Câu hỏi phỏng vấn C#
Câu hỏi

What are Nullable types in C#?

Câu trả lời

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:

csharp Copy
int? age = null;
bool? isStudent = null;

Here are some key points about nullable types in C#:

Accessing Nullable Values

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 (??).

csharp Copy
int? age = 25;
int ageValue = age.Value; // 25

age = null;
int defaultAge = age?.Value ?? 30; // 30

Nullable Operators

C# provides several operators that work with nullable types:

  1. 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.

  2. **Null-coalescing operato...

junior

junior

Gợi ý câu hỏi phỏng vấn

expert

List some different ways for equality check in .NET

middle

Why can't you specify the accessibility modifier for methods inside the Interface?

expert

Could you explain the difference between destructor , dispose and finalize method?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào