#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

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: