How to create custom method in predefined class C#?

Custom Method C#, Add Existing Method to Predefined Class, C#, Advanced C#

Jul 30, 2023 - 13:53
Jul 30, 2023 - 13:57
 0
How to create custom method in predefined class C#?

In C#, you can create a custom method in a predefined class using extension methods. Extension methods allow you to add new methods to existing classes without modifying the original class's source code. This can be useful when you want to add functionality to classes from third-party libraries or system classes.

To create a custom method in a predefined class using an extension method, follow these steps:

  1. Define a static class to contain your extension method. The class should be static and non-generic.

  2. Define a static method within the static class, and use the this keyword with the first parameter to indicate which class you are extending. The this parameter represents the instance of the class that the extension method will be applied to.

Here's a step-by-step guide with an example:

Suppose we want to create a custom method to calculate the square of an integer in the int data type's predefined class.

  1. Create a new static class to hold the extension method:
public static class IntExtensions
{
    // Custom extension method to calculate the square of an integer
    public static int Square(this int number)
    {
        return number * number;
    }
}

Now you can use the Square() method on any integer variable as if it were a built-in method:

using System;

class Program
{
    static void Main()
    {
        int myNumber = 5;
        
        // Using the custom Square() method on the integer variable
        int squaredValue = myNumber.Square();
        Console.WriteLine($"Square of {myNumber} is: {squaredValue}");
    }
}

Output:

Square of 5 is: 25

In the example above, we created a custom extension method Square() for the int data type. The method is defined in the IntExtensions class, and it can now be called on any int variable, just like any other built-in method.

Remember that extension methods must be defined in a static class and should be placed in a static namespace to be accessible throughout your application. Also, be mindful of naming conflicts and choose meaningful and unique names for your custom methods.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow

Dr. Deepak Kumar Experienced Managing Director with a demonstrated history of working in the information technology and services industry. Skilled in Management · Team Building · Cloud Migration · Market Research · Team Leadership · Research Projects · New Business Development · Time Management · Analytical Skills. Strong business development professional with a Doctorate focused in Computer Programming from BIT Mesra.