What is the best way to name fields and properties

Microsoft says that fields and properties should not only differ from case to case. So, if they really represent the same idea, how should they be different?

Here is a Microsoft 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 indication as to how this should look. What do most developers do?

+6
c # naming-conventions
source share
7 answers

No, Microsoft says that publicly visible participants should not only differ from the case:

This rule only works for public members.

(This includes protected members as they are visible to derived classes.)

So this is great:

 public class Foo { private string bar; public string Bar { get { return bar; } } } 

It’s my personal rule not to allow any other private fields, in which case this is not a problem.

Do you really need protected fields? How about a property having a protected setter if you want to mutate it from derived classes?

+11
source share

This may cause some developers to be disgusting, but I like the naming conventions that allow me to immediately distinguish member variables from local residents.

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; } } } 
+7
source share

I like:

 protected string _Bar; public string Bar { get { return _Bar; } } 
0
source share

Think most developer prefix member variables have an underscore:

 protected string _bar; 
0
source share

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 initially used just _ or m_ as a prefix for all my fields, until I started digging through a lot of Microsoft.NET code through Reflector. Microsoft also uses the s_ and m_ paradigm, and I like it. This makes it easy to find out what a field is when you read the body of the function code. I don’t need to point out anything and wait for a tooltip or something like that. I know if something is static or an instance is just its field prefix.

0
source share

It is up to you or your organization / organization standard. But most programmers use camelCasing or underlining + camelCasing for fields and PascalCasing for properties such as:

 public class Foo { protected string _bar; public string Bar { get { return _bar; } } } 
0
source share

All Articles