#807 – Defining and Using an Extension Method

An extension method is a method that you define to extend an existing class without having to modify or inherit from the existing class.  The new method behaves as if it was defined as an instance method of the original class.

For example, you might define a Decorate() method that extends the System.String class.

To define an extension method:

  • Define it in a static class, as a static function
  • The 1st parameter must be of the type that you are extending and must include the this keyword on the parameter
    static class StringExtensions
    {
        public static string Decorate(this string s)
        {
            return "** " + s + " **";
        }
    }

You can now use the extension method as if it was an instance method on the System.String class.

            string s = "Fire at the triangle factory";
            Console.WriteLine(s.Decorate());

807-001

Advertisement

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

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: