Reputation: 1096
Does someone knows C# best practice about the way to define attribute visibility (private or protected) behind public property in abstract class or parent class.
In other worlds what is the best practice by default (and why) between:
public abstract class MyClass
{
private string myAttribute;
public string MyAttribute
{
get { return myAttribute; }
set { myAttribute = value; }
}
}
and
public abstract class MyClass
{
protected string myAttribute;
public string MyAttribute
{
get { return myAttribute; }
set { myAttribute = value; }
}
}
I think children class should have the way to handle directly this protected attribute but it may not be a good practice if getter or setter contains more code...
What do you think about that?
Thank you.
Upvotes: 3
Views: 8274
Reputation: 1096
I found one limitation for public get, protected set: comments. Because comments should not be the same for public and protected, respecting stylecop: - Comment for public: Gets comment - Comment for protected: Gets or sets comment
I don't want to do 2 properties for both visibility, so i resolved it quiclky with the following comment: Gets ot set (protected) comment.
If you have better practice, it's welcome.
Upvotes: 0
Reputation: 755387
Definitely private. When defining an abstract class I only make items protected if it is a behavior that meets the following
In this case you've already given external classes access to the value. Making it protected doesn't give the sub-class any real advantage.
Upvotes: 2
Reputation: 39872
Definitely private. However, there's an easier way to do what you're doing:
public abstract class MyClass
{
public string MyAttribute { get; set; }
}
This does exactly the same thing, but its a lot easier to maintain.
Upvotes: 2
Reputation: 121414
Non-const fields should be really always private. If you need to use a field because you cannot use auto-properties for some reason, make sure it's private. Children classes should access it via public or protected properties.
Upvotes: 10