What is new without type in C#?
Asked Answered
F

2

14

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?

Flense answered 4/10, 2021 at 8:6 Comment(2)
devblogs.microsoft.com/dotnet/welcome-to-c-9-0/…Marti
If possible, you should discuss the usage of this feature with your team. Dictionary<SomeVeryLongName, List<AnotherTooLongName>> _field = new() is a good use of it. Your example is not. The rule we apply is : the complete type should appear at least once, prefer var (by habit and consistency with old code).Sememe
R
15

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.

Robin answered 4/10, 2021 at 8:13 Comment(0)
L
11

The new() creates an object of a type that can be inferred from context.

So instead of:

throw new System.Exception("hi");

you can use this abbreviated form instead:

throw new ("hi");

Similarly,

var s = new string("hello");

can be replaced with:

string s = new("hello");
Lapides answered 4/10, 2021 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.