Frame<int, int>[] test = new Frame<int, int>[3] {{2,5},{3,6},{4,7}};
Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
How is that possible?
The issue here is that the literal {2,3} by itself does not represent a Frame<int, int>. It is only used as part of an initializer, which means it has to accompany an instantiation, like this:
Frame<int, int>[] test = new Frame<int, int>[]
{
new Frame<int, int>(2, 5),
new Frame<int, int>(3, 6),
new Frame<int, int>(4, 7)
};
There is a way around this. If you define a type with the following two characteristics, you can get the syntax you want:
IEnumerable. (Actually, it doesn't even need to really implement it; it just needs to be defined as implementing it. In other words the GetEnumerator method doesn't have to do anything.)Add method.Now, the Add requirement defines how the initialization syntax works. So here's an example, using a FrameCollection class designed purely for initialization of a Frame<int, int>[] array:
// Skeleton code for illustration only.
class Frame<T1, T2>
{
public Frame(T1 x, T2 y)
{
X = x;
Y = y;
}
public T1 X { get; private set; }
public T2 Y { get; private set; }
}
// IEnumerable (non-)implementation for initializer syntax.
class FrameCollection : IEnumerable
{
List<Frame<int, int>> _frames;
public FrameCollection()
{
_frames = new List<Frame<int, int>>();
}
// Add method to enable initialization syntax using { x, y }.
public void Add(int x, int y)
{
_frames.Add(new Frame<int, int>(x, y));
}
public Frame<int, int>[] ToArray()
{
return _frames.ToArray();
}
// This method doesn't technically need to do anything.
IEnumerator IEnumerable.GetEnumerator()
{
throw new InvalidOperationException();
}
}
Because the FrameCollection class defines an Add method which accepts two int parameters, we can now write code like this:
var frames = new FrameCollection
{
{ 2, 5 },
{ 3, 6 },
{ 4, 7 }
};
foreach (Frame<int, int> frame in frames.ToArray())
{
Console.WriteLine("({0}, {1})", frame.X, frame.Y);
}
Output:
(2, 5) (3, 6) (4, 7)
Are you sure it shouldn't something like this?
Frame<int, int>[] test = new Frame<int, int>[3] {
new Frame<int, int>(2,5),
new Frame<int, int>(3,6),
new Frame<int, int>(4,7)
};
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