Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 370
  • Last Modified:

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

                  System.Console.WriteLine(children.Id);
            }

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

//Halkatla
0
Halkatla
Asked:
Halkatla
1 Solution
 
nikkilockeCommented:
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,

Nikki
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now