Reputation: 41163
Microsoft says fields and properties must differ by more than just case. So, if they truly represent the same idea how should they be different?
Here's Microsoft's example of what not to do:
using System;
namespace NamingLibrary
{
public class Foo // IdentifiersShouldDifferByMoreThanCase
{
protected string bar;
public string Bar
{
get { return bar; }
}
}
}
They give no guidance on how this should look. What do most developers do?
Upvotes: 6
Views: 1120
Reputation: 8558
It depends on you or your company\organization's coding standard. But most programmers use camelCasing or underscore + camelCasing on Fields and PascalCasing on Properties like:
public class Foo
{
protected string _bar;
public string Bar
{
get { return _bar; }
}
}
Upvotes: 0
Reputation: 32950
I personally do the following:
class SomeClass
{
private static string s_foo; // s_ prefix for static class fields
private string m_bar; // m_ prefix for instance class fields
public static string Foo
{
get { return s_foo; }
}
public string Bar
{
get { return m_bar; }
}
}
I originally used to just use _ or m_ as a prefix for all of my fields until I started digging through lots of Microsoft .NET code via Reflector. Microsoft uses the s_ and m_ paradigm as well, and I kind of like it. It makes it easy to know exactly what a field is when you are reading the code body of a function. I don't have to point to anything and wait for a tooltip to appear or anything like that. I know whether something is static or instance simply by its field prefix.
Upvotes: 0
Reputation: 3986
This may make some developers out there hurl in disgust, but I like naming conventions that let me distinguish member variables from locals at a glance.
So, I often do something like:
public class Foo
{
protected string _bar;
public string Bar
{
get { return _bar; }
}
}
...or...
public class Foo
{
protected string mBar; // 'm' for member
public string Bar
{
get { return mBar; }
}
}
Upvotes: 7
Reputation: 1499860
No, Microsoft says publicly visible members must differ by more than just case:
This rule fires on publicly visible members only.
(That includes protected members, as they're visible to derived classes.)
So this is fine:
public class Foo
{
private string bar;
public string Bar { get { return bar; } }
}
My personal rule is not to allow anything other private fields anyway, at which point it's not a problem.
Do you really need protected fields? How about making the property have a protected setter if you want to be able to mutate it from derived classes?
Upvotes: 11
Reputation: 3890
Think most developers prefix member variables with underscore like so:
protected string _bar;
Upvotes: 0
Reputation: 8938
I like:
protected string _Bar;
public string Bar
{
get { return _Bar; }
}
Upvotes: 0