Adam Hollander
Adam Hollander

Reputation: 23

C# - What is the purpose of this statement in Visual C#?

I think I have a fairly basic question here. I'm not trying to waste your time, but I just didn't know what to Google to get a good answer. My question has to do with object initialization. Take the following example from the Head First C# book:

using System;
using etc...

namespace Bees
{
   public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Queen queenie = new Queen(workers, Report); //Queen is a created class
        }
        Queen queenie; //This is the line I'm curious about

        private void assignButton_Click(object sender, EventArgs e)
        {
            Report.AppendText(queenie.AssignWork(comboBox1.SelectedItem.ToString(), (int)shifts.Value));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            queenie.WorkNextShift();
        }
...

If I've already instantiated a Queen object by saying Queen queenie = new Queen(...);, what purpose does the Queen queenie line serve, and what is its scope? What key concept am I misunderstanding here?

Upvotes: 2

Views: 120

Answers (1)

Mark Byers
Mark Byers

Reputation: 838266

It looks like a bug in the code. Probably this was meant:

public Form1()
{
    InitializeComponent();
    queenie = new Queen(workers, Report);
}

Queen queenie; //This is where the reference to the constructed Queen is stored

The line Queen queenie; declares a field of type Queen that is accessible from all methods of the instance, but not from outside the class.

If you are uncertain what some of these terms mean, I suggest that you follow a more gentle tutorial:

Or if you already blew your book budget for the year then browse some of the free online documentaition:

Upvotes: 12

Related Questions