|
-
June 20th, 2009, 08:35 AM
#1
Access modifiers for get and set in properties
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?
-
June 20th, 2009, 10:49 AM
#2
Re: Access modifiers for get and set in properties
Let's look at this another way : what are the advantages of being able to specify an access modifier on both ?
Code:
public int MyProperty
{
public get { return _value; }
protected set { _value = value; }
}
Isn't this the same as :
Code:
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 :
Code:
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.
Last edited by darwen; June 20th, 2009 at 10:54 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|