.NET C# Null Handling using inbuilt operators

Abhishek Malaviya
2 min readJul 16, 2023

--

Null-coalescing operators(?? and ??=)

Instead of using the If condition and then assigning a default value, we can do it neatly by using the null-coalescing operator.

Example

public class MyClass
{
public string Message { get; set; }
public int? Count { get; set; } = null;

public MyClass(string message)
{
//Example of Null Coalescing operator(??)
Message = message ?? "Default Message";

//Example of Null Coalescing assignment operator(??=)
Count ??= 1000;

Console.WriteLine($"Message: {Message} \n Count: {Count}");
}
}

MyClass myClass = new MyClass(null);

Output

Output

Null-conditional operators (?. and ?[])

Operation to its left hand side operand only if that operand evaluates to non-null; otherwise, it returns null.

Example


public class TestNullConditionalOperator
{
private readonly Order _order;

public TestNullConditionalOperator(Order order)
{
_order = order;

//Here we are using Null Conditional Operator(?.) with Null Coalescing Operator(??).
//If _order is null then it will not throw exception and will return "Default Order".
Console.WriteLine("Example of Operator(?.)");
Console.WriteLine($"Order: {_order?.Name??"Default Order"}");

_order=new Order() { Id = 1, Name = "Order 1"};
//Here _order is not null so it will return "Order 1".
Console.WriteLine($"Order: {_order?.Name}");

List<string> listNull = null;
List<string> listNotNull = new List<string>() { "Abhishek", "Vinod" };

//Here we are using Null Conditional Operator(?[]) with Null Coalescing Operator(??).
//If listNull is null then it will not throw exception and will return "Default Value".
Console.WriteLine("\nExample of Operator(?[])");
Console.WriteLine($"ListNull First Value: {listNull?[0] ?? "Default Value"} \nListNotNull First Value: {listNotNull?[0]}");
}
}

//Order class
public class Order
{
public int Id { get; set; }
public string Name { get; set; }
}


TestNullConditionalOperator testNullConditionalOperator =
new TestNullConditionalOperator(new Order() { Id=1001});

Output

Happy coding. Thanks for reading.

--

--

No responses yet