3

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.

4 Answers 4

10

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.

1
  • for that matter, I am thinking even the containing class should only access via the property.
    – Muad'Dib
    Jan 27, 2010 at 15:38
2

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.

2
  • 1
    +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. Jan 27, 2010 at 15:43
  • Ok, I didn't know auto-implemented properties!
    – Vince
    Jan 27, 2010 at 15:50
2

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.

1
  • I am upvoting your answer, noting that it should be the CORRECT answer. Private backing fields are definitely the norm, but there are rare cases where you need to override a property. Feb 9, 2014 at 21:52
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.