POV
POV

Reputation: 12015

How to fill tuple in C#?

I have got the Tuple as:

 private Tuple<double, double, int>[] circle;

I trired to add and element using add() method. But there is not exist.

How to add element in Tuple array?

Upvotes: 0

Views: 1653

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

You cannot add elements to an array of tuples (or to array of anything else, for that matter), but you do have a number of options for creating an array of tuples:

  • You can create a fixed-size array, and then populate it later, or
  • You can create a fixed-size array, and populate it right away, or
  • You can create a List, add items to it, and convert it to an array when you are done adding elements to it.

The third option is the most flexible. This is how it looks:

var list = new List<Tuple<double,double,int>>();
list.Add(Tuple.Create(1.5, 1.7, 9));
list.Add(Tuple.Create(2.6, 3.8, 11));
circle = list.ToArray();

Upvotes: 1

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Forget tuples for a second. How do you fill any arrays?

private int[] _numbers; // now what?

The answer is that arrays, in C#, have immutable size - they must be allocated during initialization, and that's the size they have. Once you've initialized them, you can assign values to the array members by index:

_numbers = new int[5];
_numbers[0] = 5;
circle = new Tuple<double,double,int>[5];
circle[0] = new Tuple<double,double,int>(1.0, 2.0, 3);

If you're coming in from a different language and expect a variable-length array that can be added to, what you're looking for is .NET's List<T> class, which can be initialized empty, and have members added and removed.

private List<Tuple<double,double,int>> circle;
circle = new List<Tuple<double,double,int>>();
circle.Add(new Tuple<double,double,int>(3.0, 2.0, 1));

Upvotes: 3

Related Questions