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

senior

Explain what is Short-Circuit Evaluation in C#

entry

What is C#?

junior

How is Exception Handling implemented in C#?

Bình luận

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

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