Thomas
Thomas

Reputation: 93

declare list of fixed size arrays in c#

I've got a function which operates on pixels. I want to create one list with RGB values, but when I declare it this way:

List<int[]> maskPixels = new List<int[3]>();

It gives me error:

Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

Adding pixels is done like this: maskPixels.Add(new int[] { Red, Green, Blue });

Is there a way to do this, or I have to use new List<int[]>(); instead?

Upvotes: 8

Views: 7332

Answers (5)

Yaugen Vlasau
Yaugen Vlasau

Reputation: 2218

 [Flags]
    public enum RGB
    {
        R,
        G,
        B
    }

...

public List<RGB> l = new List<RGB>();
l.Add(RGB.r | RGB.G)

Upvotes: -1

jason
jason

Reputation: 241641

That's not possible. Think about it for just a second. When you have a generic type, say List<T>, T is a type parameter and for specific instances of the generic type, you fill in a type T.

But int[3] is not a type! Precisely, it's an array-creation-expression in the C# grammar.

If you want to limit to a type that can only hold three values, may I suggest as a first cut Tuple<int, int, int>? But even better, I recommend a type dedicated to representing RGB like System.Drawing.Color (use Color.FromArgb(int, int, int)) or your own custom type if necessary. The reason I would lean towards the latter is because not all Tuple<int, int, int> are valid representations of RGB!

Upvotes: 6

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

There is no way to do something similar, but since you are using this for RGB values, why don't you use Color class instead?

List<Color> maskPixels = new List<Color>();

And initialize each Color like this:

Color c = Color.FromArgb(R,G,B); //assuming R,G,B are int values 

If your values are in the range of 0-255 this is the most natural way of storing them. You have predefined getters and setters in order to obtain each color component.

Upvotes: 8

Moo-Juice
Moo-Juice

Reputation: 38825

I'd suggest having your own value-type for this:

public struct Rgb
{
    int R,
    int G,
    int B
}

List<Rgb> list = new List<Rgb>;

Upvotes: 5

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You can't do array initialization like this, and further each int[] could technically be a different size. How about a different data structure, List<Tuple<int, int, int>>?

This would allow you to strictly have three integer values in the list, and it's searchable via LINQ faster than an array because it's a well defined structure with properties.

Upvotes: 5

Related Questions