Declare a list of fixed-size arrays in C #

I have a function that works with pixels. I want to create one list with RGB values, but when I declare it as follows:

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

This gives me an error:

The size of the array cannot be specified in the variable declaration (try initializing with the "new" expression)

Adding pixels is performed as follows: maskPixels.Add(new int[] { Red, Green, Blue });

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

+6
source share
5 answers

It's impossible. Think about it for just a second. If you have a generic type, say List<T> , T is a type parameter, and for specific instances of the generic type, you populate the type T

But int[3] not a type! Exactly, this is a array-creation-expression in a C # grammar.

If you want to restrict a type that can contain only three values, can I suggest Tuple<int, int, int> as the first cut? But even better, I recommend a type designed for representing RGB, like System.Drawing.Color (use Color.FromArgb(int, int, int) ) or, if necessary, your own custom type. The reason I'm leaning toward the latter is because not all Tuple<int, int, int> are valid RGB representations!

+5
source

It is not possible to do something like this, but since you are using this for RGB values, why not use the Color class?

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

And initialize each color as follows:

 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 to store them. You have predefined getters and setters to get each color component.

+7
source

You cannot initialize an array like this, and then each int[] can be technically of a different size. What about another data structure, List<Tuple<int, int, int>> ?

This will allow you to strictly have three integer values ​​in the list and search through LINQ faster than an array, because it is a well-defined structure with properties.

+5
source

I suggest having your own value type for this:

 public struct Rgb { int R, int G, int B } List<Rgb> list = new List<Rgb>; 
+5
source
  [Flags] public enum RGB { R, G, B } 

...

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

Source: https://habr.com/ru/post/946958/


All Articles