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?
The fixed-size arrays To declare a fixed-size array, specify the type of elements and the number of elements required: <type> <array-name> [ <array-size> ]; . This is a one-dimensional array. Example: uint balance[10];
There are three different types of arrays in C: A fixed-size array is an array in which the size is known during compile time. A variable-length array (VLA) is an array in which the size is variable (known only during run-time) and is allocated on the stack.
Declaring Arrays:typeName variableName[size]; This declares an array with the specified size, named variableName, of type typeName. The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable.
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
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.
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!
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