gripmYgrip
gripmYgrip

Reputation: 13

C# encapsulation (get and set)

I am doing exercises in Head First C# book.

This code is supposed to be about encapsulation.

class DinnerParty
{
    private int NumberOfPeople;
         ....

    public void SetPartyOptions(int people, bool fancy) {
        NumberOfPeople = people;
        .....
    }

    public int GetNumberOfPeople() {
        return NumberOfPeople;
    }
}

In form1 class

public partial class Form1 : Form
{
    DinnerParty dinnerParty;
    public Form1()
    {
        InitializeComponent();

        dinnerParty = new DinnerParty() {NumberOfPeople = 5 };

        ...

Is this suppose to work?

Visual Studio is showing me an error. (cannot access due to its protection level)

I am very new at this.

Thanks

Upvotes: 1

Views: 2334

Answers (6)

Abdul Munim
Abdul Munim

Reputation: 19217

You can't initialize a private field outside your scope (class).

Make it a property.

public int NumberOfPeople { get; set; }

and now, this will work

dinnerParty = new DinnerParty() { NumberOfPeople = 5 };

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064114

No that is not supposed to work. I can't see the book, so I can't comment on the context. However:

public int NumberOfPeopoe {get;set;} 

Is a reasonable fix.

Upvotes: 0

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79979

That's becouse NumberOfPeople is private means that it can't be accessible from outside the class DinnerParty, so you need to make it public.

Upvotes: 1

0lukasz0
0lukasz0

Reputation: 3277

The NumberOfPeople is private, so it will not work. The best solution here is to create public property instead of private field or add constructor and initialize this field there.

Upvotes: 0

Ali Foroughi
Ali Foroughi

Reputation: 4629

NumberOfPeople is a private member and you can not use it out of the class dude

Upvotes: 0

Uwe Keim
Uwe Keim

Reputation: 40756

You could use the idea of a "Fluent interface" by writing something like:

class DinnerParty
{
    private int NumberOfPeople;

         ....

    public DinnerParty SetPartyOptions(int people, bool fancy) {
        NumberOfPeople = people;
        .....

        return this; // Return own instance to allow for further accessing.
    }

    public int GetNumberOfPeople() {
        return NumberOfPeople;
    }
}

And then call it:

public partial class Form1 : Form
{
    DinnerParty dinnerParty;
    public Form1()
    {
        InitializeComponent();

        dinnerParty = new DinnerParty().SetPartyOptions( 5, true );

        ...

Upvotes: 0

Related Questions