abenci
abenci

Reputation: 8651

Protected member field and its property

Suppose you have the following A class definition:

class A
{
   protected double[] _temperatures;

   double[] Temperature
   { 
      get {return _temperatures;} 
      set {_temperatures = value;}
   }
}

How should I access temperatures in a derived class B? Using the member field or the property? Should I declare _temperatures as private and always use the property? What is the overhead of using the property instead of direct member field access?

Thanks.

Upvotes: 0

Views: 89

Answers (4)

Adarsh Shah
Adarsh Shah

Reputation: 6775

Yes change the data member to private. Using a Property instead of a Field (private member) is a better way of accessing it even if its from within the same class so that if you have some logic in the getter/setter you don't have to repeat it each time you set the value.

Even if you don't have logic its better to use property as you might need to add some logic in future. It will be a single point of entry for getting and setting the value.

And yes as Kevin suggested you can use auto-implemented property if you don't have custom logic.

Upvotes: 0

node
node

Reputation: 1

Ideally a class should not expose its members (in your case _temperatures) to the outside world. Members are meant to be used internally with in a class. If you want to expose a class member then use properties. Thats ideal way of designing a class.

The advantage of this type of class designing is tomorrow suppose there is a need to add some logic when assigning a value or retrieving a value from a class member then it can be easily accomodated with in a property without redesigning the interface.

So declare _temperatures as private and expose it to derived classes by declaring the property Temperature as protected.

Refer this C# tutorial for additonal information:

Upvotes: 0

Prakash Vishwakarma
Prakash Vishwakarma

Reputation: 832

You may modify your code like this:

class A
{
    private double[] _temperatures;

    public double[] Temperature
    {
        get { return _temperatures; }
        set { _temperatures = value; }
    }
}
class B : A
{
    public B()
    {
        B b = new B();
        Console.WriteLine(b.Temperature);
    }
}

Local variable '_temperatures' should be private and property 'Temperature' should be either public or protected.

Upvotes: 0

Kevin Brechbühl
Kevin Brechbühl

Reputation: 4727

You should use the property and make the field private. But your code with a custom private field only make sense if you really need to add some custom logic in the getter or setter. So for your simple case, you can go with this:

class A
{
   protected double[] Temperature { get; set; }
}

Upvotes: 4

Related Questions