I've just noticed that when you declare a List
in c# you can put parentheses or curly braces at the end.
List<string> myList = new List<string>(); List<string> myList2 = new List<string>{};
Both these list appear to have the same functionality. Is there any actual difference caused by declaring them with parentheses or curly braces?
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
The use of curly braces { }
is called a collection initializer. For types that implement IEnumerable
the Add
method would be invoked normally, on your behalf:
List<string> myList2 = new List<string>() { "one", "two", "three" };
Empty collection initializers are allowed:
List<string> myList2 = new List<string>() { };
And, when implementing an initializer, you may omit the parenthesis ()
for the default constructor:
List<string> myList2 = new List<string> { };
You can do something similar for class properties, but then it's called an object initializer.
var person = new Person { Name = "Alice", Age = 25 };
And its possible to combine these:
var people = new List<Person> { new Person { Name = "Alice", Age = 25 }, new Person { Name = "Bob" } };
This language feature introduced in C# 3.0 also supports initializing anonymous types, which is especially useful in LINQ query expressions:
var person = new { Name = "Alice" };
They also work with arrays, but you can further omit the type which is inferred from the first element:
var myArray = new [] { "one", "two", "three" };
And initializing multi-dimensional arrays goes something like this:
var myArray = new string [,] { { "a1", "b1" }, { "a2", "b2" }, ... };
Update
Since C# 6.0, you can also use an index initializer. Here's an example of that:
var myDictionary = new Dictionary<string, int> { ["one"] = 1, ["two"] = 2, ["three"] = 3 };
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