Adding custom methods to your classes can be a great way to extend the functionality of those classes. You can use them to define new types of methods that can be called from other classes, or even from other methods within the same class.
The C# programming language provides support for writing custom methods which are used to write user defined logic. In this programming tutorial, we will take a look at custom methods in C# with relevant code examples..
Before we begin, you may want to check out a few of our tutorials discussing classes, objects, and object oriented programming (OOP) if you are unfamiliar with the topics or need a refresher:
What is a Custom Method in C#?
A custom method is a user-defined method that contains a specific set of code instructions. In C#, custom methods must be declared within a class or struct. Custom methods can be used to perform a variety of tasks, such as initializing an object, calculating a value, or modifying data.
Custom methods help developers to:
- Organize code properly
- Reuse a piece of code if needed
- Define custom business logic
Custom methods must be created by specifying the access modifier (such as public or private), then the return type, name, and any parameters.
The following is the syntax for declaring a custom method in C#:
(Parameter List) { Method Body }
Let us now understand each of the elements of the preceding code example in detail:
- Access Specifier: This represents the visibility level of your method, i.e., whether the method is visible outside the class, the assembly, etc. The access specifier of a method can be public, protected, internal, protected internal, and private.
- Return type: This represents the return type of the method. A method that does not return any value should have a void return type.
- Method name: This defines the name of the method. Remember that method name is unique in a class. You cannot have two methods having the same names and signatures in a class.
- Parameter list: This represents the list of parameters you can pass to the method as arguments when the method is invoked. Remember that parameters are optional, i.e., programmers may or may not have parameters defined in a method.
- Method body: This refers to the block of code you will write to execute your custom logic. This is also known as the method body.
For more on method parameters, check out our tutorial: What are C# Method Parameters?
How to Create Custom Methods in C#
The following C# code example creates a custom method named AddIntegers that takes two integers as parameters and returns an integer result:
public int AddIntegers(int num1, int num2) { return (num1 + num2); }
The following code listing shows a custom method defined in a class named Repository. This method returns true if a user is active and the user id is passed to the method as an argument. If the user is not active, it returns false:
public class Repository { public bool IsActive(int id) { //Write your custom code here to connect to the database and check if //the user is active return true; //This method returns true just to satisfy the compiler. } }
How to Create Custom Extension Methods in C#
In C#, the term extension method refers to a method that can be applied to an existing type even if it does not belong to that type. They provide a way to add functionality to existing types without modifying the type.
It should be noted that extension methods are implemented as static methods, and they are declared through the this keyword and they should be a part of a non-generic static class.
The primary benefit of extension methods is that they allow developers to add methods to types that do not support them by default.
The following code example shows how an extension method can be defined in C#:
public static class MyExtensions { public static bool IsNumber(this string str) { int i; return int.TryParse(str, out i); } }
Now consider the following piece of code:
string str = "Hello World"; bool isNumeric = str.IsNumber();
When you execute the preceding code, the bool variable isNumeric will have a value of “false“.
If you store a number in the string variable str, the isNumber extension method would return true:
string str = "12345"; bool isNumeric = str.IsNumber();
Read: Top Online Courses to Learn C#
How to Create Custom Overloaded Methods in C#
The C# programming language allows programmers to define methods that have identical names but that differ in their signatures. This concept is known as method overloading. Method overloading can improve the readability of code and make your code efficient, readable, reusable, and maintainable.
The following code shows how you can overload methods in C#:
public class DBManager { public void Add(DataSet dataSet) { //Write your code here to insert data from the DataSet instance to //the data store. } public void Add(DataTableReader dataTableReader) { //Write your code to insert data from the DataTableReader instance to //the data store. } }
In the preceding code example, note how the two methods have been defined – they both have the same names but they differ in the parameters.
The following code example shows another example of custom methods in C#. Note how – the method Add has been overloaded:
public class Helper { public static int Add(int x, int y) { return x + y; } public static double Add(double x, double y) { return x + y; } }
You can learn more about method overloading in our tutorial: How to Overload Methods in C#.
Final Thoughts on Creating Custom Methods in C#
The C# programming language provides a lot of flexibility to create your own methods, define your custom logic inside it, and return one or more values if needed. By taking advantage of this flexibility, we can create powerful and useful custom methods for our applications.