views:

75

answers:

4

Trying to do everything by the book, is this correct?:

public class JollyHockey
{
    public string AnotherCoolProperty { get { return anotherCoolProperty; } }

    string anotherCoolProperty;

    public JollyHockey(string anotherCoolProperty)
    {
         this.anotherCoolProperty = anotherCoolProperty;
    }
}

Or do some people use underscores for the private class variables?

+4  A: 

Or you can do this:

public class JollyHockey
{
    public string AnotherCoolProperty { get; private set; }

    public JollyHockey(string anotherCoolProperty)
    {
        this.AnotherCoolProperty = anotherCoolProperty;
    }
}
Jon B
+1 for suggesting the private setter. I like your answer more than Justin Niessner's because prefixing private variables with an underscore looks really ugly to me. :)
jloubert
+4  A: 

Some people (including myself) prefix private class variables with an underscore (simply as a visual indication of what is being used where).

This is mainly a personal (or team) level style consideration and you can use what you want (or what your team has standardized on).

Just be sure you're consistent!

For what it's worth, you could also use auto-properties for your example:

public class JollyHockey
{
    public string AnotherCoolProperty { get; private set; }
    public JollyHockey(string anotherCoolProperty)
    {
        AnotherCoolProperty = anotherCoolProperty;
    }
}
Justin Niessner
Had never heard of auto-properties. Fantastic!
Andrew White
A: 

I believe that your example agrees with the MS coding guidelines. However, I don't like it, and this is something that can be agreed upon by your team.

The reason I don't like it is because the underlying field name often conflicts with method parameters. I use an underscore to make it clear that they are private variables.

Ed Swangren
A: 

When a function parameter has the same name as a private field,

I usually prefix the parameter with an underscore

I think it makes sense

the ReSharper thing By fletcher is a good idea

camilin87