Home > Posts > Suggestion: Allow new in C# without giving Type

Suggestion: Allow new in C# without giving Type

This is a suggestion I’ve just sent in via Visual Studio’s “Send a frown” feature:

Instead of writing statements like:

List<CultureInfo> result = new List<CultureInfo>();

in C# I’d prefer to be able to write

List<CultureInfo> result = new ();

inside the () one would be able to pass contructor parameters and also they should be able to use

SomeClass v = new (someParam) { someProperty = …, otherProperty = … };

syntax, that is be able to initialize properties of the class

What I mean is that I want to omit the type name after the new, since it is deduced from the type I have given to the new var.

Doing

Type v = new (…){…};

is more general from the alternative of doing

  var v = new Type(…){…};

since you would be also able to even do

  someCollectionType.Add(new (…){…});

to add a new member to a typed collection

and also would be able to do

SomeMethod(new (…){…})

where the Type would be deduced from the param of the method (obviously if it is not overloaded with more versions with just 1 param)

Update:

In fact, now that I think of it again, the concept of anonymous types in C# could be merged with the suggested one, making the (…) optional if no constructor parameters are to be used (in anonymous types you only give the {…} part with the properties’ initialization).

The compiler would then resort to making a new anonymous type only if it can’t deduce a type from the usage context.

Of course if the (…) part (constructor parameters) are given, it would never try to make an anonymous type if it can’t find a matching type to instantiate with the respective constructor signature to call.

Have uploaded this for voting up at:

http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/9453546-allow-new-in-c-without-giving-type

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: