Towhid
Towhid

Reputation: 2084

How I will use the following static variable from other class?

I have a class like following:

public class Trainee
{

    private static int numberOfTrainee = 30;

    private string traineeName;
    private string tarineeId;
}

Now I want to access the static data "numberOfTrainee" in the following class without creating a object of "Trainee" class and I don't want to write getter for "numberOfTrainee". Because, static member can be used only using "." operator.

public class TraineeUI : Form
{
   private void showButton_Click(object sender, EventArgs e)
    {
        // I want to access "numberOfTrainee" here. Something like following:
        // MessageBox.Show("Total number of trainee is: " );

    }
}

Upvotes: 1

Views: 3244

Answers (4)

Matthew Abbott
Matthew Abbott

Reputation: 61589

I don't want to recycle what others have said, but....

You need to look at access modifiers. You say you don't want to make numberOfTrainee public, but you can make it internal. That way, if Trainee and TraineeUI are in the same assembly, than TraineeUI can access the field of Trainee without the field being exposed to types outside the assembly.

I would make it a property instead of a field though.

Upvotes: 1

Rich
Rich

Reputation: 3101

If you don't want a getter for it, the only way to use it from elsewhere will be to increase the visibility, like so:

public class Trainee
{
    public static int NumberOfTrainee = 30;
    private string traineeName;
    private string tarineeId;
}

// Other code.
MessageBox.Show("Total number of trainee is: " + Trainee.NumberOfTrainee);

However, I would recommend against doing this with a field that can change. Unless it's a constant, you should define a property to control access to this field, static or not.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500525

You should make a property, like this:

public class Trainee
{    
    private static int numberOfTrainee = 30;

    public int TraineeCount { get { return numberOfTrainee; } }

    private string traineeName;
    private string tarineeId;
}

Note that you may want to consider thread safety... it's possible that this simple implementation will give stale results in a multi-threaded environment. Making numberOfTrainee volatile would solve this.

Further, note that by making this a property rather than giving direct access to the field, you:

  • Can add extra logic should you ever wish to
  • Can make the property readonly, but modify the field from within the class
  • Keep encapsulation intact: a property is part of the API of a class, whereas a field is an implementation detail

Upvotes: 3

Hans Olsson
Hans Olsson

Reputation: 55009

Well, either you could make it public and then just calll it with:

Trainee.numberOfTrainee

Or you could create a static readonly property.

public static int NumberOfTrainee
{
    get
    {
        return numberOfTrainee;
    }
}

Upvotes: 0

Related Questions