In this C#.Net tutorial, we will discuss a complete guide on the c#.net method naming conventions. We will see, method naming conventions in C#.Net related to:
- c#.net private method naming conventions
- c#.net static method naming conventions
- c#.net generic method naming conventions
- c#.net bool method naming conventions
- c#.net public method naming conventions
- c#.net protected method naming convention
- c#.net method parameter naming conventions
- c#.net async method naming conventions
C#.net method naming conventions
A naming convention is a set of rules for choosing the character sequence to be used for identifiers in code. Consistent naming conventions enhance the predictability and readability of the code.
Here is the guideline for C#.net method naming conventions.
General Guidelines
- PascalCasing: Method names in C# are typically named using PascalCasing – the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
CalculateSum
. - Clarity: The name should clearly express what the method does. If necessary, use more than one word. For example,
CalculateSum
,PrintReport
,CreateNewEmployee
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using abbreviations. For example,
CalculateSum
is better thanCalcSum
. - Verb or Verb-Object: Use a verb or verb-object pair such as
Show
,CalculateSum
,PrintReport
,CreateNewEmployee
. - No Underscores: Underscores are typically not used in method names in C#.
Examples
Here are examples of well-named methods:
public int CalculateSum(int a, int b)
{
return a + b;
}
public void PrintReport(Report report)
{
// code to print the report
}
public Employee CreateNewEmployee(string name, string position)
{
return new Employee(name, position);
}
public void UpdateEmployeeDetails(Employee employee, string name, string position)
{
employee.Name = name;
employee.Position = position;
}
In each case, the name of the method clearly indicates what the method does. The CalculateSum
method is expected to calculate and return the sum of two numbers, the PrintReport
method is expected to print a report, the CreateNewEmployee
method is expected to create a new employee, and the UpdateEmployeeDetails
method is expected to update the details of an employee.
These names are meaningful, self-explanatory, and follow the C#.NET method naming conventions.
C# Private Method Naming Conventions
In C#.Net, the naming convention for private methods is generally the same as public methods, as both should be clear and descriptive of their functionality.
Guidelines
- PascalCasing: This is the most common convention for private methods, where the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
CalculateAverage()
. - Clarity: Make sure the name clearly communicates what the method does. For example,
CalculateAverage()
,FindMaximumValue()
,SortEmployeeList()
. - Verb or Verb-Object: Use a verb or verb-object pair such as
Show()
,CalculateAverage()
,FindMaximumValue()
,SortEmployeeList()
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using them.
CalculateAverage()
is better thanCalcAvg()
. - Underscores: Unlike some other languages, underscores are typically not used in method names in C#.
Example
Here is an example of a well-named private method in C#.Net with proper naming conventions:
private int CalculateAverage(int[] numbers)
{
int sum = 0;
for (int i = 0; i < numbers.Length; i++)
{
sum += numbers[i];
}
return sum / numbers.Length;
}
In this case, CalculateAverage
clearly indicates what the method does: it calculates and returns the average of an array of numbers. This name is meaningful, self-explanatory, and follows the C#.Net private method naming conventions.
C#.NET Public Method Naming Conventions
Public methods in C#.Net are methods that are accessible from any class or method in the application. They play a crucial role in object-oriented programming as they define the interface of a class. Therefore, their naming is important for the readability and maintainability of the code.
Guidelines
- PascalCasing: Public methods in C# should be named using PascalCasing, where the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
CalculateTotal
. - Clarity: The name should clearly express what the method does. For example,
CalculateTotal
,GetCustomerDetails
. - Verb or Verb-Object: Use a verb or verb-object pair such as
CalculateTotal
,GetCustomerDetails
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using them. For example,
CalculateTotal
is better thanCalcTot
. - No Underscores: Underscores are typically not used in method names in C#.
Examples
Here are examples of well-named public methods:
public class Order
{
private List<Item> _items;
public decimal CalculateTotal()
{
decimal total = 0;
foreach (var item in _items)
{
total += item.Price;
}
return total;
}
}
public class CustomerService
{
public Customer GetCustomerDetails(int customerId)
{
// Code to get customer details from a database or an API
}
}
In the above example, CalculateTotal
and GetCustomerDetails
are public methods. CalculateTotal
calculates the total price of all items in an order, and GetCustomerDetails
gets the details of a customer. The method names are meaningful, self-explanatory, and follow the C#.NET public method naming conventions.
C#.Net Protected Method Naming Conventions
Protected methods in C#.Net are methods that are accessible within their class and by derived class instances. These methods are part of the class’s internal implementation and can also be part of its external interface when the class is inherited.
Guidelines
- PascalCasing: Protected methods in C#.net should be named using PascalCasing. In this convention, the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
ProcessData
. - Clarity: The name should clearly express what the method does. For example,
ProcessData
,CalculateAverage
. - Verb or Verb-Object: Use a verb or verb-object pair such as
ProcessData
,CalculateAverage
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using them. For example,
ProcessData
is better thanProcData
. - No Underscores: Underscores are typically not used in method names in C#.
Examples
Here are examples of well-named protected methods:
public class MyBaseClass
{
protected void ProcessData(string data)
{
// Code to process the data
}
}
public class MyDerivedClass : MyBaseClass
{
public void PerformAction(string data)
{
// The protected method can be accessed in a derived class
ProcessData(data);
}
}
The example above ProcessData
is a protected method. It can be accessed within its class MyBaseClass
and by a derived class instance as shown in MyDerivedClass
. The method name ProcessData
is meaningful, self-explanatory, and follows the C#.NET protected method naming conventions.
C#.NET Method Parameter Naming Conventions
Method parameters in C#.Net are variables that accept values when a method is called. They are an essential part of methods as they allow data to be passed into methods. Therefore, naming method parameters clearly is crucial for code readability and maintainability.
Guidelines
- camelCasing: Method parameters in C#.Net should be named using camelCasing. In this convention, the first letter of the identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example,
customerName
,orderNumber
. - Descriptive and Meaningful: Parameter names should be descriptive and meaningful. They should clearly indicate the kind of data they are expected to receive. For example,
customerName
,productPrice
. - Single Word Preferred: If possible, use a single word that clearly describes the type of data the parameter represents. For example,
price
,name
. If necessary, compound words can be used. - Avoid Abbreviations and Acronyms: Unless the abbreviation or acronym is widely accepted and understood, avoid using them. For example,
customerName
is better thancustName
. - No Underscores: Underscores are typically not used in parameter names in C#.
Examples
Here are examples of well-named method parameters:
public class Customer
{
public void SetDetails(string customerName, int age, string address)
{
// Code to set the details
}
}
public class Order
{
public void PlaceOrder(string productName, int quantity, decimal price)
{
// Code to place the order
}
}
In the examples above, customerName
, age
, address
, productName
, quantity
, and price
are method parameters. They are named in camelCasing and are descriptive and meaningful, indicating the kind of data they are expected to receive. They follow the C#.NET method parameter naming conventions.
C#.Net Static Method Naming Conventions
In C#.Net, static methods are methods that belong to the class itself, rather than to an instance of the class. The naming conventions for static methods are the same as for instance methods.
Guidelines
- PascalCasing: Use PascalCasing where the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
GetUpperCase
. - Clarity: The name should clearly express what the method does. For example,
GetUpperCase
,CountWords
. - Verb or Verb-Object: Use a verb or verb-object pair such as
GetUpperCase
,CountWords
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using abbreviations. For example,
GetUpperCase
is better thanGetUC
. - No Underscores: Underscores are typically not used in method names in C#.
Examples:
Here are examples of well-named static methods related to string manipulation:
public static class StringManipulation
{
public static string GetUpperCase(string input)
{
return input.ToUpper();
}
public static int CountWords(string input)
{
return input.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
// Usage:
string country = "United States of America";
string upperCaseCountry = StringManipulation.GetUpperCase(country);
int wordCount = StringManipulation.CountWords(country);
In the example above, GetUpperCase
and CountWords
are static methods. They clearly indicate what they do: GetUpperCase
converts the input string to upper case, and CountWords
counts the number of words in the input string. The method names are meaningful, self-explanatory, and follow the C# static method naming conventions.
C#.NET Generic Method Naming Conventions
Generic methods in C#.Net are methods that are declared with type parameters. They make it possible to defer the specification of one or more types until the method is called. The naming conventions for generic methods are the same as for non-generic methods, but you need to indicate the type parameter in the method declaration.
Guidelines
- PascalCasing: Use PascalCasing where the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
AddItem
. - Clarity: The name should clearly express what the method does. For example,
AddItem
,FindItem
. - Verb or Verb-Object: Use a verb or verb-object pair such as
AddItem
,FindItem
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using abbreviations. For example,
AddItem
is better thanAddItm
. - No Underscores: Underscores are typically not used in method names in C#.
Example
Here is an example of a well-named generic method:
public class MyGenericClass<T>
{
private List<T> _items = new List<T>();
public void AddItem(T item)
{
_items.Add(item);
}
public bool FindItem(T item)
{
return _items.Contains(item);
}
}
In the example above, AddItem
and FindItem
are generic methods. They clearly indicate what they do: AddItem
adds an item to the list, and FindItem
checks if an item is in the list. The method names are meaningful, self-explanatory, and follow the C#.NET generic method naming conventions.
C#.NET Boolean Method Naming Conventions
Boolean methods in C#.Net are methods that return a boolean value. These methods often check a certain condition and return either true or false. The naming convention for boolean methods is slightly different from other methods because the name should reflect the question that the method answers.
Guidelines
- PascalCasing: Use PascalCasing, in which the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
IsValid
. - Question Phrase: The name should be in the form of a question phrase, as it answers a question by returning true or false. For example,
IsValid
,HasAccess
,CanExecute
. - Avoid Negative Questions: Try to avoid negative question phrases, as they can be confusing. Instead of
IsNotValid
, useIsValid
and negate the result if necessary. - Clarity: The name should clearly express what question the method answers. The clearer the question, the easier it is to understand the method’s purpose.
- No Underscores: Underscores are not typically used in method names in C#.
Examples
Here are examples of well-named boolean methods:
public class Order
{
public DateTime? ShippedDate { get; set; }
public bool IsShipped()
{
return ShippedDate.HasValue;
}
}
public class User
{
public string Role { get; set; }
public bool IsAdmin()
{
return Role == "Admin";
}
public bool CanAccess(string resource)
{
// Assume CheckAccess is a method that checks if this user can access the given resource
return CheckAccess(resource);
}
}
In the examples above, IsShipped
, IsAdmin
, and CanAccess
are boolean methods. Their names are in the form of a question and indicate what question they answer. The names are meaningful, self-explanatory, and follow the C#.NET boolean method naming conventions.
C#.NET Async Method Naming Conventions
Async methods in C#.Net are methods that use the async
keyword and usually return Task
or Task<T>
. These methods are used for asynchronous programming, a style of programming where potentially blocking tasks are allowed to complete without blocking the execution of the rest of the program.
The naming convention for async methods includes appending “Async” to the method name, in addition to following the general method naming conventions.
Guidelines
- PascalCasing: Use PascalCasing where the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example,
GetPopulationAsync
. - Clarity: The name should clearly express what the method does. For example,
GetPopulationAsync
,CalculateTaxAsync
. - Verb or Verb-Object: Use a verb or verb-object pair such as
GetPopulationAsync
,CalculateTaxAsync
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using them. For example,
GetPopulationAsync
is better thanGetPopAsync
. - Append Async: Append “Async” to the method name. This makes it clear that the method is asynchronous and should be awaited or should be run with
Task.Run
. - No Underscores: Underscores are typically not used in method names in C#.
Examples
Here are examples of well-named async methods:
public class USStatisticsService
{
public async Task<int> GetPopulationAsync(string state)
{
// Code to get the population of the state
// This is an asynchronous method, so it should be awaited
await Task.Delay(1000); // Simulate async operation
return 0; // Return dummy data
}
public async Task<decimal> CalculateTaxAsync(int income)
{
// Code to calculate tax based on income
// This is an asynchronous method, so it should be awaited
await Task.Delay(1000); // Simulate async operation
return 0; // Return dummy data
}
}
In the examples above, GetPopulationAsync
and CalculateTaxAsync
are async methods. They clearly indicate what they do and that they are asynchronous methods. The method names are meaningful, self-explanatory, and follow the C#.NET async method naming conventions.
Conclusion
In C#.NET, adhering to method naming conventions is a key factor in writing clean, understandable, and maintainable code. These conventions apply to various types of methods, including private, public, protected, static, async, and generic methods, as well as methods returning boolean values and methods with parameters.
Here are the key takeaways:
- PascalCasing: The first letter of the identifier and the first letter of each subsequent concatenated word should be capitalized. For example,
CalculateTotal
. - Clarity: The name should clearly express what the method does. For example,
GetCustomerDetails
. - Verb or Verb-Object: Use a verb or verb-object pair such as
CalculateTotal
,GetCustomerDetails
. - Avoid Abbreviations: Unless it’s a widely accepted abbreviation, avoid using them. For example,
CalculateTotal
is better thanCalcTot
. - No Underscores: Underscores are typically not used in method names in C#.
Additionally, specific naming conventions apply to certain types of methods:
- For async methods, append “Async” to the method name to clearly indicate that the method is asynchronous.
- For boolean methods, phrase the method name as a question that the method answers.
- For method parameters, use camelCasing and ensure the parameter name is descriptive and meaningful.
By following these conventions, you can write C#.NET code that is easy to read and understand, which is beneficial for both you and anyone else who might work with your code in the future.
You may also like the following C#.Net tutorials:
- ASP.NET Control Naming Conventions
- How to create a console application in visual studio code?
- How to create a GUID in C#.Net
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…