Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of this code in c#

Tags:

java

c#

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);           
          }};
like image 675
Srikar Doddi Avatar asked Nov 27 '22 08:11

Srikar Doddi


2 Answers

In C# 3.0 or greater,

var constants = new List<double> { 1.4, 0.4, 1.2, 2.4, 4.2, 5D, 6D, 7D };

constantsis implicitly typed toList<double>with thevarkeyword. 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 theDs, 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 image 124
Ani Avatar answered Dec 06 '22 16:12

Ani


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.

like image 20
SLaks Avatar answered Dec 06 '22 15:12

SLaks