Null-conditional Operator can be used with C# with Example



Null-conditional Operator can be used with C# with Example

Extension Method 
Extension Method can work on null references, but you can use ?. to null-check anyway. 
public class Person 
{ 
public string Name {get; set;} 
} 
public static class PersonExtensions 
{ 
public static int GetNameLength(this Person person) 
{ 
return person == null ? -1 : person.Name.Length; 
} 
} 
Normally, the method will be triggered for null references, and return -1: 
Person person = null; 
int nameLength = person.GetNameLength(); // returns -1 
Using ?. the method will not be triggered for null references, and the type is int?: 
 

Person person = null; 
int? nameLength = person?.GetNameLength(); // nameLength is null. 
This behavior is actually expected from the way in which the ?. operator works: it will avoid making instance 
method calls for null instances, in order to avoid NullReferenceExceptions. However, the same logic applies to the 
extension method, despite the difference on how the method is declared. 
For more information on why the extension method is called in the first example, please see the Extension 
methods - null checking documentation. 
 

The nameof operator allows you to get the name of a variable, type or member in string form without hard-coding 
it as a literal. 
The operation is evaluated at compile-time, which means that you can rename a referenced identifier, using an 
IDE's rename feature, and the name string will update with it. 

0 Comment's

Comment Form