C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Null PropagatorC# Null Propagator is an operator. It is used to check null value in an object reference chain. This operator is a combination of two symbols, question mark (?) and comma (,). In C# code, if we call a method or property by using null object, compiler throws System.NullReferenceException exception. We receive this exception if we don't check for null in our code. To avoid this exception, we can use null propagator operator. In the following example, we are checking for null reference, by using if block, before calling a method. C# Example without using Null Propagatorusing System; namespace CSharpFeatures { class Student { public string Name { get; set; } public string Email { get; set; } } class NullConditionalOperator { public static void Main(string[] args) { Student student = new Student() { Name = "Rahul Kumar"}; // Checking for null value if(student.Name != null) { Console.WriteLine(student.Name.ToUpper()); } } } } Output Rahul Kumar In the following example, we are using Null Propagator Operator to check null reference. C# Example with Null Propagator Operatorusing System; namespace CSharpFeatures { class Student { public string Name { get; set; } public string Email { get; set; } } class NullConditionalOperator { public static void Main(string[] args) { Student student = new Student() { Name="Peter", Email = "peter@abc.com"}; Console.WriteLine(student?.Name?.ToUpper() ?? "Name is empty"); Console.WriteLine(student?.Email?.ToUpper() ?? "Email is empty"); Student student1 = new Student(); Console.WriteLine(student1?.Name?.ToUpper() ?? "Name is empty"); Console.WriteLine(student1?.Email?.ToUpper() ?? "Email is empty"); } } } Output PETER [email protected] Name is empty Email is empty
Next TopicC# String Interpolation
|