Background
.Net Console.WriteLine is null safe.
But, then some functions may not be.
To protect yourself in the case of nullable variables, please consider the use of the ?? operator.
Code
using System; class HelloWorld { static void Main() { contactList(); } static void contactList() { string friendMale; string friendFemale; string neighbor; string gender; string genderUnknown = "Unknown"; friendMale = "sampson"; Console.WriteLine ( "Friend {0} is a {1}" , friendMale , "Male" ); friendFemale = "delilah"; Console.WriteLine ( "Friend {0} is {1}" , friendFemale , "Female" ); neighbor = "Sallie"; gender = null; // traditional Console.WriteLine ( "Friend {0} is {1}" , neighbor , gender ); //Long Form if (gender == null) { Console.WriteLine ( "Friend {0} is {1}" , neighbor , genderUnknown ); } else { Console.WriteLine ( "Friend {0} is {1}" , neighbor , gender ); } //short form //use operator ?? Console.WriteLine ( "Friend {0} is {1}" , neighbor , gender ?? genderUnknown ); } //method } // class
Output
Image
Textual
Friend sampson is a Male Friend delilah is Female Friend Sallie is Friend Sallie is Unknown Friend Sallie is Unknown
References
- Microsoft
- Learn > .NET > C# guide > Language reference > Operators and expressions
- ?? and ??= operators (C# reference)
Link
- ?? and ??= operators (C# reference)
- Learn > .NET > C# guide > Language reference > Operators and expressions
[…] .Net:- Operator – The null-coalescing operator ?? Date Published:- 2022-November-8th Link […]