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?
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?
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, throw
ing 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.
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");
© 2022 - 2024 — McMap. All rights reserved.
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, prefervar
(by habit and consistency with old code). – Sememe