Null-conditional Operator can be used with Extension Method

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents