Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best name fields and properties

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?

like image 281
User1 Avatar asked Feb 10 '10 23:02

User1


1 Answers

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?

like image 195
Jon Skeet Avatar answered Oct 01 '22 02:10

Jon Skeet