tags:

views:

206

answers:

4

Hi,

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.

+6  A: 

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.

DrJokepu
for that matter, I am thinking even the containing class should only access via the property.
Muad'Dib
+2  A: 

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.

David Pfeffer
+1, This is useful when there is no special processing that needs to be done in the getters/setters. You can also restrict visibilty on getters and setters with public and private.
FrustratedWithFormsDesigner
Ok, I didn't know auto-implemented properties!
Vince
+1  A: 

Definitely private. When defining an abstract class I only make items protected if it is a behavior that meets the following

  1. Sub classes must override or have access to
  2. External classes should not have access to

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.

JaredPar
thanks to all of you
Vince
A: 

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.

Vince