1

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?

5 Answers 5

7

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, you could use !niz[6].HasValue
5

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 (i.e. no default empty items).

4 Comments

Is it true to say that default(char) should be used in case of generics and instead it should be HasValue ?
@PKKG if you are using generic array, then use default(T) instead of default(char)
can you please clarify one point about the usage priority in this context? Hasvalue or default(char)
@PKKG sorry, don't get what you are asking about. HasValue is for Nullable<T> type.
1

Because you are using chars, you need to say:

if (niz[6] == '\0') Console.WriteLine("6th is empty");

Chars cannot be equal to null.

2 Comments

It should be '\0' and not '0'
Woops, will change it now.
0

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];

Comments

0
 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);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.