Taking target-typed new expressions further #3909
Answered
by
HaloFour
shawnshaddock
asked this question in
General
-
With the new target-typed new expressions, would it be possible to also drop the new keyword and just use type initializers? This would call the parameterless constructor. //Current syntax
PrintCustomer(new Customer { FirstName = "Scott", LastName = "Hunter" });
//C# 9 syntax
PrintCustomer(new { FirstName = "Scott", LastName = "Hunter" });
//Proposed syntax
PrintCustomer({ FirstName = "Scott", LastName = "Hunter" }); This would be especially great when initializing nested types PrintCustomer(
{
FirstName = "Scott",
LastName = "Hunter",
Address =
{
Street = "One Microsoft Way",
City = "Redmond"
}
}); |
Beta Was this translation helpful? Give feedback.
Answered by
HaloFour
Sep 18, 2020
Replies: 1 comment 1 reply
-
That would be a breaking change as an object initializer can already omit public class Person {
public Address Address { get; set; } = new Address();
}
public class Address {
public string Street { get; set; }
public string State { get; set; }
}
public class C {
public void M() {
// initializes Person with a new instance of Address
var person1 = new Person {
Address = new() { // equiv to new Address()
Street = "123 Main St.",
State = "NY"
}
};
// initializes Person using the existing instance of Address
var person2 = new Person {
Address = {
Street = "123 Main St.",
State = "NY"
}
};
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
333fred
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That would be a breaking change as an object initializer can already omit
new
in order to initialize an existing instance: