开发者

C# style: May properties be grouped with their backing fields?

开发者 https://www.devze.com 2023-03-07 07:18 出处:网络
I like to organize simple properties like this: private int foo; publ开发者_如何学Pythonic int Foo

I like to organize simple properties like this:

private int foo;
publ开发者_如何学Pythonic int Foo
{
    get { return foo; }
    set
    {
        // validate value
        foo = value;
    }
}

I've been playing around with StyleCop, and it yells at me for placing fields after constructors. Is this style generally accepted, as long as the field is never referenced outside of the property? Note: I realize that there is personal preference involved, but I am wondering if there is a general consensus regarding this issue.


Yes, that seems reasonable to me.

Typically I put all the fields and properties at the top, then the constructors, then the methods - but if you want to put them after the constructors, that seems reasonable too.


If your properties are going to be simple data access consider using auto properties:

public int Foo { get; set; }

The compiler will create a private member variable behind the scenes on your behalf.

Specifically to your question, don't put too much stock in tools like ReSharper or StyleCop. Some of the ways they format code, and the things they complain about are truly a matter of preference. I do not put the member variables near their public properties, but I can see how this would be convenient.


May? Since this only affects people on your team, you have to figure out what they think is best and go with that. Style Cop is often a bit... overboard on its recommendations.

I usually put them after the property, as the space above is reserved for documentation.

// placed up here, it looks kinda weird, imho
// private int foo;
/// <summary>
/// The index of the Foo in the <see cref="Bar"/>
/// </summary>
public int Foo
{
    get { return foo; }
    set
    {
        // validate value
        foo = value;
    }
}
private int foo;


It may be a matter of preference, but this seems better than having them mixed with private members.

I usually use a nested region for backing fields inside the properties region since it doesn't interfere with visual studio comments and yet they are grouped toghether.

0

精彩评论

暂无评论...
验证码 换一张
取 消