Sergey Shishkin

on agile software development

C# Extension Methods vs. NullReferenceException

From the client’s perspective extension methods look exactly as methods of the instance itself. Except that they are actually static and therefore can accept a null reference as an argument. That gives us ability to call extension methods on null references without fear of getting a NullReferenceException:

public static CustomerSummary ToContract(this Customer customer)


    return customer == null ? null :

        new CustomerSummary


            Id = customer.Id,

            FirstName = customer.FirstName,

            LastName = customer.LastName




public void DomainToContract_NullForDomain_ReturnsNull()


    Customer expected = null;

    CustomerSummary actual = expected.ToContract();



I like it 🙂


Written by Sergey Shishkin

27.06.2008 at 11:46

Posted in Uncategorized

%d bloggers like this: