简体   繁体   中英

Property visibility in abstract class

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.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM