C# Intermediate - Extension Methods


What Are Extension Methods?

Extension methods are a way of enabling you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original class, struct or interface. An extension method is a special kind of static method but they can be called in a way that an instance methods would be called.
Extension methods can drastically improve code readability and maintainability of a code base ( if done correctly ).

 How To Use Extension Methods?

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type that is to be extended should be the first parameter of the method.
The extension methods are only available for use if it is in scope, So make sure the namespace is imported into your source code with a using directive.

We will look at 3 examples of possible use cases.
Use case 1: Extending the Int type 
using System;

namespace BitshiftProgrammer
{    
    public static class IntExtension
    {
        public static bool IsEven(this int i)
        {
            return (i%2 == 0);
        }
        public static bool IsNegative(this int i)
        {
            return (i < 0);
        }
        public static int GetSquare(this int i)
        {
            return i*i;
        }
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            int i = 10;
            Console.WriteLine("Is i even ? = " + i.IsEven());
            Console.WriteLine("Is i negative ? = " + i.IsNegative());
            Console.WriteLine("Square of i = " + i.GetSquare());
        }
    }
}
Is i even ? = True
Is i negative ? = False
Square of i = 100
Use case 2: Extending the String type 
using System;
namespace BitshiftProgrammer
{    
    public static class StringExtension
    {
        public static int SpaceCount(this string s)
        {
            int spaceCount = 0;
            for(int i = 0;i < s.Length;i++)
            {
                if(s[i] == ' ')
                    spaceCount++;
            }
            return spaceCount;
        }
        public static bool IsInCaps(this string s)
        {
            for(int i=0;i < s.Length;i++)
            {
                if(s[i] != char.ToUpper(s[i]))
                    return false;
            }
            return true;
        }
        public static int NumberOfChars(this string s, char c)
        {
            int count = 0;
            for(int i=0;i<s.Length;i++)
            {
                if(s[i] == c)
                    count++;
            }
            return count;
        }
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            string test = "Hello, My Name Jeff";
            Console.WriteLine("Space count = " + test.SpaceCount());
            Console.WriteLine("Is in all capitals = " + test.IsInCaps());
            Console.WriteLine("Number of 'y's = " + test.NumberOfChars('y'));
        }
    }
}
Space count = 0
Is in all capitals = True
Number of 'y's = 0
Use case 3: Extending an Enum type 
using System;
namespace BitshiftProgrammer
{    
    public enum Direction {LEFT, RIGHT, FRONT, BACK };
    public static class DirectionEnumExtension
    {
        public static Direction GetOppositeDirection(this Direction dir)
        {
            switch(dir)
            {
                case Direction.LEFT : return Direction.RIGHT;
                case Direction.RIGHT : return Direction.LEFT;
                case Direction.FRONT : return Direction.BACK;
                case Direction.BACK : return Direction.FRONT;
            }
            return Direction.FRONT;
        }
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            Direction dir = Direction.LEFT;
            Console.WriteLine("Opposite of left is = " + dir.GetOppositeDirection());
        }
    }
}
Opposite of left is = RIGHT
Extending an enum is really useful thing to do especially when that enum is being used in multiple places throughout your code base.
Several more such use cases are there such as extending an interface or an abstract class.
Well I hope you learnt something of value.
Please do support Bitshift Programmer by sharing this with your friends and colleagues.
For More C# Tutorials, go HERE.
For Unity Tutorials, go HERE.