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?
It is used to create objects and invoke a constructor. Using the "new" operator, we can create an object or instantiate an object, in other words with the "new" operator we can invoke a constructor. Let's create a class for example: public class Author.
The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint.
We can create an object without creating a class in PHP, typecasting a type into an object using the object data type. We can typecast an array into a stdClass object. The object keyword is wrapped around with parenthesis right before the array typecasts the array into the object.
We can Create objects in C# in the following ways: 1) Using the 'new' operator: A class is a reference type and at the run time, any object of the reference type is assigned a null value unless it is declared using the new operator.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With