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';
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).
You could do:
test[2] = Char.MinValue;
If you had tests to see if a value was "null" somewhere in your code, you'd do it like this:
if (test[someArrayIndex] == Char.MinValue)
{
// Do stuff.
}
Also, Char.MinValue == default(char)
you can set test to null
test = null;
but not test[2] because it is char - hence value type
I don't know the reason for your question, but if instead you use List<>
, you could say
List<char> test = new List<char> { a, b, c, };
test.RemoveAt(2);
This changes the length (Count
) of the List<>
.