I have on very simple array in C#:
char[] niz = new char[16];
niz[0] = 'c';
niz[1] = 's';
niz[2] = 'h';
niz[3] = 'a';
niz[4] = 'r';
niz[5] = 'p';
How can I check which element of this array is empty?
I've tried this code:
if (niz[6] == null) Console.WriteLine("6th is empty");
But in this case it's not empty, and I don't know why.
Can you help me with this please?
You need to use nullable types. change this to
char?[] niz = new char?[16];
then your code will work
if (!niz[6].HasValue)
Console.WriteLine("6th is empty");
Array will be initialized with default values of array element type. Char is not a reference type, so null
is not default value for it. For char default is 0
.
You can check array[i] == default(char)
, but this will not tell you if array item is empty, or it has default value assigned by you:
char[] niz = new char[16];
niz[0] = 'c';
niz[1] = (char)0; // default value
niz[2] = '\0'; // default value
niz[3] = 'a';
niz[4] = 'r';
niz[5] = 'p';
for(int i = 0; i < niz.Length; i++)
Console.WriteLine(niz[i] == default(char));
As Ehsan suggested, you can use array of nullable chars, but again, you will not know whether item is not initialized, or you have assigned null
value to it. I suggest you to use List<T>
class instead of array. It will contain only items you need (ie no default empty items).
Because you are using chars, you need to say:
if (niz[6] == '\\0') Console.WriteLine("6th is empty");
Chars cannot be equal to null.
The problem is that char will be initialized with a default value. You need to make it nullable like this:
char?[] niz = new char?[16];
char[] niz = new char[16];
niz[0] = 'c';
niz[1] = 's';
niz[2] = 'h';
niz[3] = 'a';
niz[4] = 'r';
niz[5] = 'p';
for (int i = 0; i < niz.Length; i++)
{
if (niz[i] == '\0') Console.WriteLine(i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.