#812 – Defining an Extension Method for a Value Type

You can define an extension method against any type, including both reference types and value types.

Here’s an example of an extension method that adds functionality to the int (System.Int32) type.

    static class MyExtensions
    {
        public static int Triple(this int i)
        {
            return i * 3;
        }
    }

The Triple method now acts as an instance method that we can invoke on any variable of type int or even on an integer constant.

            int i = 123;
            Console.WriteLine(i.Triple());

            Console.WriteLine(12.Triple());

812-001

Advertisement