Skip to content

MathlaALw/ExtensionAndReflection

Repository files navigation

Extenstion in C#

Extension

Extension Method is a special kind of static method that allows you to "extend" an existing class or interface with new methods without modifying the original type’s code and without creating a derived type.

Key Points:

  • Must be declared in a static class.
  • Must be a static method.
  • The first parameter specifies the type being extended and is preceded by the this keyword.
  • Can be called as if it were a method of the extended type.

Syntax of Extension Method in C#

public static class ExtensionClass
{
	public static ReturnType MethodName(this Type parameter, OtherParameters)
	{
		// Method implementation
	}
}

When to Use:

  • To add helper methods to existing classes .

  • Want more readable code.

  • To reduce code duplication.

Example of Extension 1

public static class StringExtensions
{
	public static bool IsNullOrEmpty(this string str) 
	{
		return string.IsNullOrEmpty(str); 
	}
}

In this example, we define an extension method IsNullOrEmpty for the string class, allowing us to call it as if it were a method of the string class itself.

How to use:

string myString = null;
bool result = myString.IsNullOrEmpty();
Console.WriteLine(result); 

Output:

True

Example of Extension 2

using System;

public static class StringExtensions
{
    // Extension Method
    public static bool IsCapitalized(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        return char.IsUpper(str[0]);
    }
}

class Program
{
    static void Main()
    {
        string name = "Code";
        string word = "codeline";

        Console.WriteLine(name.IsCapitalized());  // True
        Console.WriteLine(word.IsCapitalized());  // False
    }
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages