manymanymore
manymanymore

Reputation: 3108

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?

Upvotes: 14

Views: 5791

Answers (2)

Camilo Terevinto
Camilo Terevinto

Reputation: 32053

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.

Upvotes: 15

Phillip Ngan
Phillip Ngan

Reputation: 16126

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");

Upvotes: 12

Related Questions