Reference type constant initializing and Array concetanation
1) const int[] array={1,2,3,4}; //this gives below error
"Error 1 'ConsoleApplication1.Main.array' is of type 'int[]'.
A const field of a reference type other than string can only be initialized with null"
In my 开发者_开发技巧opinion according to error messeagge, it is not meaningfull to use const for reference types.Am i wrong ?
2) How can i concatenate int array ? Example:
int[] x={1,2,3} + {4,5,6};
I know that + operator will not work so what is best way to do it as strings ?
Concat extension method do that. Not high clarity code but does.
(new int[] { 1, 2, 3, 4 }).Concat(new int[] { 5, 6, 7, 8 }).ToArray();
1) Yes, the only reference type that is any useful as constant is String.
2) To concatenate arrays you create a new array and copy the contents of the arrays to it:
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] x = new int[a.Length + b.Length];
a.CopyTo(x, 0);
b.CopyTo(x, a.Length);
I don't know what you count as the "best" method, but this is the most effective. (A quick test shows that this is 10-20 times faster than using the Concat
extension method.)
精彩评论