java – What is the equivalent of this code in c# – Education Career Blog

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 };

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 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.

,

The above is simply a static list initialisation, so the equivalent in C# would be:

new List<Double>(){ 1.4, 0.4 } 

Note that the Java code above actually creates a new inner class which is a subclass of ArrayList, and then initialises it. You wouldn’t normally have to worry about this, but it’s worth knowing (it will have an implicit this pointer, and cause headaches when serialising)

,

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

,

Using an inner class is probably not the best way to do it in Java. You’d probably want to do something like

List<Double> constants = Arrays.asList(new Double{1.4,0.4,1.2,2.4,4.2,5.0,6.0,7.0});

Leave a Comment