List<Double> constants = new ArrayList<Double>() {{
add(1.4);
add(0.4);
add(1.2);
add(2.4);
add(4.2);
add(5);
add(6.0);
add(7.0);
}};
In C# 3.0 or greater,
var constants = new List<double> { 1.4, 0.4, 1.2, 2.4, 4.2, 5D, 6D, 7D };
constants
is implicitly typed toList<double>
with thevar
keyword. The list is initialized (by putting the numbers in braces) using the collection-initializer syntax.
This is equivalent to (C# 2.0 or greater):
List<double> constants = new List<double>();
constants.Add(1.4);
constants.Add(0.4);
constants.Add(1.2);
constants.Add(2.4);
constants.Add(4.2);
constants.Add(5D);
constants.Add(6D);
constants.Add(7D);
You can leave out theD
s, but I prefer to be explicit with numeric literals.
On another note, if this really represented a list of unnamed constants, it would be good to use an immutable collection such as ReadOnlyCollection<T>
. For example:
var constants = new List<double>{1.4, 0.4, 1.2, 2.4, 4.2, 5, 6, 7}.AsReadOnly();
Like this:
List<Double> constants = new List<Double>() { 1.4, 0.4, ... };
This uses a new feature in C# 3.0.
If you're still using VS2005, you can write
List<Double> constants = new List<Double>(new double[] { 1.4, 0.4, ... });
This is not quite the same.
The first line is transformed by the compiler into a series of Add
calls on the list.
The second line creates a double[]
array and passes it to the List<T>
constructor, which copies it to the list.
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