Click to See Complete Forum and Search --> : Access modifiers for get and set in properties


LibertyOrDeath
June 20th, 2009, 08:35 AM
Hi all,

This is a general question. I'm currently teaching myself C# from a textbook so I'm a relative newbie to the language, although I already know Java and C++ so I'm not finding it too difficult to pick up.

I've just covered a section on properties for objects. The book says that access modifiers may be specified for either the set or get accessor of a property, where the access modifier must be more restrictive than that of the property itself, i.e.

public int MyProperty
{
protected get
{
// Do something
}

set
{
// Do something else
}
}

The book says that an access modifier can be specified for either set or get but not both. It doesn't explain why this is the case though. Why can't it be both? What was the rationale for this rule when C# was created? What are the benefits of this restriction?

darwen
June 20th, 2009, 10:49 AM
Let's look at this another way : what are the advantages of being able to specify an access modifier on both ?


public int MyProperty
{
public get { return _value; }
protected set { _value = value; }
}


Isn't this the same as :


public int MyProperty
{
get { return _value; }
protected set { _value = value; }
}


So one access method inherits its access from the specifier for the property, one doesn't. It doesn't therefore give you anything to be able to specify access for both get and set since there are only 2 access methods available.

And this :


public int MyProperty
{
protected get { return _value ; }
protected set { _value = value; }
}


would be nonsense if permissable : you've declared a public property which doesn't have any public access methods.

Hence at least one accessor must exhibit the same access as its parent property for the property to be valid and hence the restriction.

Darwen.