Use of unassigned local variable

Hello to all experts! :o)

In a project, I have created my own class to make siblings-objects. A sibling-object shall only be created if the childArray has elements. Why do I get the error "Use of unassigned local variable children" in the writeline-line?

            public static void Main(){
                  string[] childArray = {"child 1", "child 2"};

                  wSiblings children;

                  if (childArray.Length > 0){
                        children = new wSiblings();
                        children.Id = 1;


What am I missing or have forgotten about c#-programming?

Who is Participating?
nikkilockeConnect With a Mentor Commented:
Hi Halkatla,

If childArray.Length was == 0, then children would not have been set to anything, so you the compiler complains to you.

If you added

children = null;

for example, (either outside the if, or in an else to it), then children would always be assigned to, so the compiler wouldn't complain.

Hope this helps,

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.