Tutorial by Examples

Using the null-coalescing operator (??) allows you to specify a default value for a nullable type if the left-hand operand is null. string testString = null; Console.WriteLine("The specified string is - " + (testString ?? "not provided")); Live Demo on .NET Fiddle This is l...
The left-hand operand must be nullable, while the right-hand operand may or may not be. The result will be typed accordingly. Non-nullable int? a = null; int b = 3; var output = a ?? b; var type = output.GetType(); Console.WriteLine($"Output Type :{type}"); Console.WriteLine($&q...
The null coalescing operator makes it easy to ensure that a method that may return null will fall back to a default value. Without the null coalescing operator: string name = GetName(); if (name == null) name = "Unknown!"; With the null coalescing operator: string name = GetN...
A common usage scenario that this feature really helps with is when you are looking for an object in a collection and need to create a new one if it does not already exist. IEnumerable<MyClass> myList = GetMyList(); var item = myList.SingleOrDefault(x => x.Id == 2) ?? new MyClass { Id = 2...
private List<FooBar> _fooBars; public List<FooBar> FooBars { get { return _fooBars ?? (_fooBars = new List<FooBar>()); } } The first time the property .FooBars is accessed the _fooBars variable will evaluate as null, thus falling through to the assignment statement ass...

Page 1 of 1