Search code examples
c#new-operatorsyntactic-sugar

What is new without type in C#?


What is new without type in C#?

I met the following code at work:

throw new("some string goes here");

Is the new("some string goes here") a way to create strings in C# or is it something else?


Solution

  • In the specific case of throw, throw new() is a shorthand for throw new Exception(). The feature was introduced in c# 9 and you can find the documentation as Target-typed new expressions.

    As you can see, there are quite a few places where it can be used (whenever the type to be created can be inferred) to make code shorter.

    The place where I like it the most is for fields/properties:

    private readonly Dictionary<SomeVeryLongName, List<AnotherTooLongName>> _data = new();
    

    As an added note, throwing Exception is discouraged as it's not specific enough for most cases, so I'd not really recommend doing throw new ("error");. There are quite a lot of specific exceptions to use, and if none of those would work, consider creating a custom exception.