When initializing a new List in C#, both of following will compile:
(1) List<string> s = new List<string>() { "value" };
and
(2) List<string> s = new List<string> { "value" };
What is the difference between case 1 and case 2?
When initializing a new List in C#, both of following will compile:
(1) List<string> s = new List<string>() { "value" };
and
(2) List<string> s = new List<string> { "value" };
What is the difference between case 1 and case 2?
This rings true for any type. Generally, you specify the ()
if you need to pass something to the types constructor that it doesn't expose for setting publically. If there's no parameters needed, the ()
are just fluff.
Consider the scenario that you may want to do some additional validation/logic to a property and you don't allow direct manipulation of it:
public class Foo
{
private string Bar { get; set; }
public string FooBar { get; set; }
public Foo (string bar)
{
Bar = bar + "foo";
}
}
So this is allowed:
var foo = new Foo("bar")
{
FooBar = "foobar"
};
Yet this isn't:
var foo = new Foo
{
Bar = "bar",
FooBar = "foobar"
};
There are some C# types that only allow you to set certain properties within the constructor.
There is no difference. It will be translated as:
List<string> s1 = new List<string>();
s1.Add("value");
List<string> s2 = new List<string>();
s2.Add("value");
From 7.6.10.1 Object creation expressions of the C# reference 5.0:
An object creation expression can omit the constructor argument list and enclosing parentheses provided it includes an object initializer or collection initializer. Omitting the constructor argument list and enclosing parentheses is equivalent to specifying an empty argument list.
The latter is called Object Initialization. You may also use MyClass m = new MyClass { MyVar = 3 };