for example when I wrote:
Char[] test = new Char[3] {a,b,c};
test[2] = null;
it says Cannot convert null to 'char' because it is a non-nullable value type
if I need to empty that array of char, is there a solution?
for example when I wrote:
Char[] test = new Char[3] {a,b,c};
test[2] = null;
it says Cannot convert null to 'char' because it is a non-nullable value type
if I need to empty that array of char, is there a solution?
Use a nullable char:
char?[] test = new char?[3] {a,b,c};
test[2] = null;
The drawback is you have to check for a value each time you access the array:
char c = test[1]; // illegal
if(test[1].HasValue)
{
char c = test[1].Value;
}
or you could use a "magic" char value to represent null, like \0:
char[] test = new char[3] {a,b,c};
test[2] = '\0';
default(char) for the "magic" value. IMHO, it provides a similar mental model for considering the value "uninitialized" or "unspecified."\0 as null is a holdover from my C++ days :)You can't do it because, as the error says, char is a value type.
You could do this:
char?[] test = new char?[3]{a,b,c};
test[2] = null;
because you are now using the nullable char.
If you don't want to use a nullable type, you will have to decide on some value to represent an empty cell in your array.
As the error states, char is non-nullable. Try using default instead:
test[2] = default(char);
Note that this is essentially a null byte '\0'. This does not give you a null value for the index. If you truly need to consider a null scenario, the other answers here would work best (using a nullable type).
default(char) gives the null character. Why not make that explicit and say test[2] = '\0';? I would recommend that (if you want to use this character as a kind of "magic value").default in many cases where the type is not know up front (i.e. generics or reflection). It helps me keep a consistent mental model that default => "unspecified" or "uninitialized."