Saturday, May 13, 2023

What is extension method in c#?| Extension method in c#| extension method

What is extension method in c#?


 An extension method in C# is a static method that allows you to add new functionality to an existing class or interface without modifying its source code. Extension methods are called as if they were instance methods on the extended type, but are defined in a separate static class.


Here is an example of an extension method in C#:



static class StringExtensions

{

    public static string Capitalize(this string str)

    {

        if (string.IsNullOrEmpty(str))

        {

            return str;

        }


        return char.ToUpper(str[0]) + str.Substring(1);

    }

}



In this example, we define an extension method called `Capitalize()` for the `string` class. The `this` keyword before the first parameter indicates that this is an extension method for the `string` class.


We can then call the `Capitalize()` method on any `string` object, as if it were an instance method defined in the `string` class:



string myString = "hello world";

string capitalizedString = myString.Capitalize(); // "Hello world"



In this example, calling the `Capitalize()` method on the `myString` object returns a new `string` object with the first character capitalized, demonstrating the use of an extension method in C#.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...