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<\/code> ,
throw new()<\/code> is a shorthand for
throw new Exception()<\/code> .
The feature was introduced in c# 9 and you can find the documentation as Target-typed new expressions<\/a> .
private readonly Dictionary<SomeVeryLongName, List<AnotherTooLongName>> _data = new();
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");
The new()<\/code> creates an object of a type that can be inferred from context.
throw new System.Exception("hi");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.