Extension methods in C# 3.0 – null „dereferencing“

When you start with C# studying then one of first thesis is that you always should be sure if reference type is not null because if we will work with null then we can get NullReferenceException. What do you think about following C# 3.0 code?

List<string> list = null;

One can say that compilation will fail because there is no ToMyString method on List<T> type. But this code will be compiled successfully and won’t throw NullReferenceException! It’s possible due to extension method – new feature of C# 3.0. This is implementation of ToMyString method:

public static class MyExtensions
    public static string ToMyString(this object o)
        return o == null ? "null" : o.ToString();

Extension method is static method that is placed in static class and that has „this“ keyword before its first parameter. Type of the first parameter is very important because it determines type that will be enriched. If we are in (or we are using) the namespace where static class is defined then we call extension method as instance method of this type.
If we will have look at generated CIL code then we can see that there is only one difference between regular static method and extension method – extension method and its static class is decorated by System.Runtime.CompilerServices.ExtensionAttribute attribute. If we call one of these methods then generated code is identical.
And this is the reason why we can call extensions methods on null references – the first code I showed is the same as this code:

List<string> list = null;

So thanks to extension methods we can see code that seams to throw NullReferenceException…interesting…

Zanechat odpověď

Vyplňte detaily níže nebo klikněte na ikonu pro přihlášení:

Logo WordPress.com

Komentujete pomocí vašeho WordPress.com účtu. Odhlásit /  Změnit )

Google photo

Komentujete pomocí vašeho Google účtu. Odhlásit /  Změnit )

Twitter picture

Komentujete pomocí vašeho Twitter účtu. Odhlásit /  Změnit )

Facebook photo

Komentujete pomocí vašeho Facebook účtu. Odhlásit /  Změnit )

Připojování k %s

Tento web používá Akismet na redukci spamu. Zjistěte více o tom, jak jsou data z komentářů zpracovávána.