Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
manymanymore Avatar asked Oct 04 '21 08:10

manymanymore


People also ask

What is new () C#?

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.

Why do we use new in C#?

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.

Can I create object without class?

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.

Can we create object without class in C#?

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.


2 Answers

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.

like image 171
Camilo Terevinto Avatar answered Oct 03 '22 07:10

Camilo Terevinto


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");
like image 31
Phillip Ngan Avatar answered Oct 03 '22 06:10

Phillip Ngan