I have something similar to the code below. InheritedThing is a char[]? property in the base class.
✅This works:
string mystring = "hello";
char[] ca = { mystring[0] };
InheritedThing = ca;
❌This shortcut does not:
string mystring = "hello";
InheritedThing = { mystring[0] };
It gives me the red squigglies under the curly braces. Why?
Is it because the IDE can't determine what kind of array I'm passing? If so, how do I typecast the anonymous array so that it knows it is a char[]?
CodePudding user response:
Here are your options for making a new char array initialized to a value (without relying on a method that returns a char array):
//when you're declaring the variable too
char[] c = new char[] { 'x' };
char[] c = new[] { 'x' };
char[] c = { 'x' };
var c = new char[] { 'x' };
var c = new[] { 'x' };
//when assigning to an existing variable, new keyword I required
Thing = new char[] { 'x' };
Thing = new[] { 'x' };
I tend to use the new[] { ... } shortcut everywhere, because it works consistently regardless the context (unless the c# version is too old to permit it). Might also be worth noting that in cases where the compiler is figuring out the type for the array, it just uses the first element so you're allowed to put different types as long as they're implicitly convertible to the type of the first
var nums = new[] { 1m, 1, 'a' };
This ends up as a decimal[] because an int and a char can be implicitly converted to it (char becoming the numeric index of its position in the character table, so 'a' is 97)
CodePudding user response:
Addressing a saner way to do it: you can use the string's .ToCharArray method, which takes the start index and desired length:
InheritedThing = mystring.ToCharArray(0, 1);
CodePudding user response:
You can retain the brackets syntax by adding new [] right before the brackets:
char[] InheritedThing;
var mystring = "hello";
InheritedThing = new[] { mystring[0] };
