Coding Conventions and Best Practices for .NET and C# Developers (Part 1)

C# Naming Conventions

1. Use Pascal casing for class names, method names and namespaces.

public class MyClass
void MyMethod()
namespace MyApplication.Web

2. Use Camel casing for variable names and method parameters.

int myInt = 0;
void AddPerson(string firstName, string lastName);

3. Use Pascal casing for interface name along with ‘I’ as prefix.

public interface IMyInterface

4. Use meaningful and descriptive variable names.

Good: string studentName
Bad: string stdName

Coding Best Practices

1. Properly indent code using TABs.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i<numbers.length; i++)
{
  Console.WriteLine(i);
}

2. Use a blank line to separate logical groups of code.

string firstName = “Prasanna”;
string lastName = “Pandey”;

string fullName = firstName + lastName;

3. Use a blank line to separate two methods.

4. Keep member variables and properties at the top of the file.

5. Avoid writing long methods. Instead re-factor long methods into separate methods with specific tasks.

6. Use logical name for method names. Method name should tell what is does.

string GetStudentNameByStudentId(int studentId) { }

7. When using conditional block, always watch for unexpected values.

if (accontType == “Registered User”) { }
else if (accountType == “AnonymousUser”) { }
else { // handle the unexpected value }

8. Do not hard code strings. User resource files as much as possible.

9. Convert strings to lowercase or uppercase before comparing.

10. Use ‘enum’ whenever required.

enum AccountType
{
  RegisteredUser,
  AnonymousUser
}

void CheckAccountType(AccountType accountType)
{
  switch (accountType)
  {
    case AccountType.RegisteredUser:
    break;

    case AccountType.AnonymousUser:
    break;

    default:
    break;
  }
}

11. Keep member variables as private and expose then using public/protected properties.

12. Never hard code application path in code. Get application path programmatically and use relative path.

13. Show friendly and meaningful response messages to user

14. Use ‘internal’ for class, methods and properties, if they are accessed only within the same assembly

15. Avoid creating methods with too many parameters. In those cases, use a model class or a structure as parameters

16. Close database connections, sockets, file streams etc. after use

17. Use ‘StringBuilder’ class to concatenate strings, specially inside loops

Add comment