X

Default literal expressions in C# 7.1

C# 7.1 introduces a little update to default literal expressions that makes them a little bit shorter and on some cases helps us write cleaner and more readable code. This blog post introduces this litlle feature update in C# 7.1 and peeks behind the compiler to see what is produced of default literal expressions.

Old style default literal expressions

Default literal expressions let us use default values for types. I think most of my readers know default keyword from C#. Here are some samples from previous versions of C#.

public static class DefaultLiteralExpressions
{
    public static bool OldStyle()
    {
        var i = default(int);
        var o = default(object);

return i.Equals(o);
    }

    private static int OldMethodWithArgs(int i = default(int), object o = default(object))
    {
        return default(int);
    }
}

New style default literal expressions

C# 7.1 adds some syntactic sugar to default keyword and default expression doesn’t require type to be specified anymore if it is possible for compiler to find it out.

public static class DefaultLiteralExpressions
{
    public static bool NewStyle()
    {
        int i = default;
        object o = default;

return i.Equals(o);
    }

    private static int NewMethodWithArgs(int i = default, object o = default)
    {
        return default;
    }

    private static T NewMethodWithArgs<T>(int i = default, object o = default)
    {
        return default;
    }
}

New default literal expressions work also with method arguments and return values.

Are new and old default literal expressions the same?

To answer the question let’s build the demo code using Release configuration. After this we remove PDB-file from output directory to remove all reference information about actual code and open DLL-file using JetBrains dotPeek.

public static class DefaultLiteralExpressions
{
    public static bool OldStyle()
    {
        return 0.Equals((object)null);
    }

    private static int OldMethodWithArgs(int i = 0, object o = null)
    {
        return 0;
    }

    public static bool NewStyle()
    {
        return 0.Equals((object)null);
    }

    private static int NewMethodWithArgs(int i = 0, object o = null)
    {
        return 0;
    }

    private static T NewMethodWithArgs<T>(int i = 0, object o = null)
    {
        return default(T);
    }
}

Comparing old and new style code we can see that default literal expressions are the same.

Wrapping up

Default literal expressions in C# are syntactic sugar but it’s still useful feature for language. When comparing old and new style defaults in code examples above we can see that new defaults let us write a little bit shorter code that is also easier to read as there are fewer parenthesis and type names involved.

Liked this post? Empower your friends by sharing it!
Categories: C#

View Comments (0)

Related Post