#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #812 – Defining an Extension Method for a Value Type

  1. Pingback: Dew Drop – April 2, 2013 (#1,518) | Alvin Ashcraft's Morning Dew

Leave a comment