Warning: Trying to access array offset on value of type null in /home/customer/www/mozartec.com/public_html/wp-content/plugins/pressapps-login-access/includes/skelet/path.php on line 408
Extension Methods In C# - Mozartec
Mozart Al Khateeb

Full Stack

Mobile

.Net Developer

ERP Developer

Mozart Al Khateeb

Full Stack

Mobile

.Net Developer

ERP Developer

Blog Post

Extension Methods In C#

March 17, 2019 Programming
Extension Methods In C#

Extension methods are used to extend a class’s functionality.
when are extension methods useful ?

  • extend a class’s functionality that we can not modify and have no access to its source code.
  • keep code clean by writing simple methods that can give us more features .

Steps

Create a static class that will house our static extension method, This method returns if the supplied int is greater than the int we are working on.

public static class Extension
{
    public static bool IsGreaterThan(this int input, int secondValue)
    {
        return input > secondValue;
    }
}

Call the extension Method.

int intToTestAgainst = 23;

int secondInt = 25;

var isGreater = intToTestAgainst.IsGreaterThan(25);

Console.WriteLine($"Is {intToTestAgainst} > {secondInt} ? \n {isGreater}"); 

Console.ReadLine();

Extension methods can work on any type of class where they can solve more complex problems but this is a simple example to let you understand how it works.

Taggs:
Write a comment