Skip to content

Instantly share code, notes, and snippets.

@rickyah
Last active August 29, 2015 13:58
Show Gist options
  • Save rickyah/10016045 to your computer and use it in GitHub Desktop.
Save rickyah/10016045 to your computer and use it in GitHub Desktop.
CSharper_naming_conventions

#C# Naming conventions

Why bother?

Using this naming conventions will allow to know if we are dealing with local variables, private fields, or public data just with a glimpse of the code.

In this code: ¿which variables are internal data to the class and which ones are public?

public void MyMethod(int index)
{
   var DataList = GetListForIndex(index);
   
   foreach(var value in DataList)
   {
    	if (value == Index && EnableEditing)
    	{
    	    currentIndex = value;
    	    CurrentIndex = RecomputeInternalValue(currentIndex);
    	}
    	
   }

After reading this document, you should be able to answer the previous question in an easier way for this code:

public void MyMethod(int index)
{
   var dataList = GetListForIndex(index);
   
   foreach(var value in dataList)
   {
    	if (value == _currentIndex && _isEditingEnabled)
    	{
    	    _currentIndex = value;
    	    CurrentIndex = RecomputeInternalValue(_currentIndex);
    	}
    	
   }

### General rule

PascalCase all the way:

public class MyClass 
{
    public MyClass()
    {
    }
    
    private int GetAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything()
    {
    	return 42;
    }
}

### Local variables

camelCase

public class MyClass 
{
    public MyClass()
    {
    }
    
    public int GetAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything()
    {
    	int theMeaningOfLife = 42;
    	
    	return theMeaningOfLife;
    }
}

###Fields

Public fields: PascalCase

public class MyClass 
{
    public float Speed;
}

Private or protected fields: _camelCase

public class MyClass 
{
    protected float _speed;
    
    private bool _isEnabled;
}

Properties


Always PascalCase (no mather its access modifier)

public class MyClass 
{
    public float Speed {get;set;}
    public bool IsEnabled {get; protected set;}
    private string Name {get;set;}
}

### Special case: fields/properties/methods returning boolean

Prefix with "Is", "Has" or any english construct that denotes a question:

public class MyClass 
{
    public bool AreSubcomponentsInitialized;
    public bool IsEditingEnabled {get; protected set;}
    private bool HasBuildingAttached() {return false;}
    protected bool _isUpdateEnabled
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment