#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

#811 – Extension Methods Can Only Access Public Members of Class

When you write an extension method to extend the behavior of an existing class, the code in your extension method has access only to the public members of the class being extended.  Even though the code that you are writing acts as a new instance method on the class, the code within your method has no special access to the members of the class beyond its public members.

#810 – Where Extension Methods Came From

Extension methods were introduced into the C# language as part of version 3.0 of the language, introduced in November of 2007.  C# 3.0 was part of the same release that included version 3.5 of the .NET Framework.

Extension methods are a language mechanism that can be used in a variety of circumstances.  They were included in the language, however, to help support the features of LINQ (Language Integrated Query), which was also introduced in November, 2007, as part of .NET Framework 3.5.

LINQ includes a large number of extension methods that extend the existing System.Collections.Generic.IEnumerable<T> class, which was part of .NET Framework 2.0.  Adding this functionality by way of extension methods allowed LINQ to operate on standard collections, rather than introducing a new LINQ-specific collection class.

810-001

#809 – Extension Method Signatures Shouldn’t Match Class Methods

The idea of writing an extension method is to create a method that can be invoked in the same way as one of the instance methods of a class.  You can’t override an existing instance method using an extension method, but only add new methods.

If you author an extension method that has the exact same signature as an existing instance method in the class, the compiler won’t complain about your new method.  But if you try invoking the method, the original instance method will be called, rather than your extension method.

    static class StringExtensions
    {
        // Will never get called
        public static int CompareTo(this string s1, string s2)
        {
            return 0;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string s = "Pan Am";
            int n = s.CompareTo("KLM");    // Original CompareTo method called

            Console.ReadLine();
        }
    }

#808 – Adding Parameters to an Extension Method

When you define an extension method, the first parameter of your method represents the instance that you want the method to act upon.  You can, however, add additional parameters.

An extension method that acts on a string, for example, would have string as the first parameter and then, optionally, some other parameters.

        public static string Decorate(this string s, string frontDec, string backDec)
        {
            return frontDec + " " + s + " " + backDec;
        }

When you invoke the method, you pass in these additional parameters.

            // Using the extension method
            string s = "Salk announces polio vaccine";
            string dec = s.Decorate("<<==", "==>>");
            Console.WriteLine(dec);

808-002

Notice that Intellisense now lists the new extension method as an option for the string type and correctly lists two parameters.
808-001

#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

#802 – A Method Might Have No Parameters

You can pass one or more data values to a method using parameters.  A parameter in a method is just a variable, usable only within that method, that refers to a piece of data passed into the method.

If the method that you are writing requires no data to be passed in, you can omit all parameters.  You include an empty pair of parentheses after the method name, to indicate that the method has no parameters.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // All data that we need is passed into constructor
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        // Bark is a method that has no parameters
        public void Bark()
        {
            Console.WriteLine(string.Format("{0} : WOOF !", Name));
        }
    }

#774 – Passing an Array as an out Parameter

Like other reference types, you can use an array as an output parameter, using the out keyword.  The out keyword indicates that you must assign a value to the array before returning from the method.  Also, within the method, you cannot reference the array parameter before you assign a new value to it.

        static int FindFibsThrough(int numFibs, out int[] fibs)
        {
            // Can't reference element of array
            //int i = fibs[0];

            // Can't assign to element of array
            //fibs[0] = 12;

            if (numFibs < 2)
                throw new Exception("Must return at least 2 numbers in sequence");

            // Must assign new value to array before we return
            fibs = new int[numFibs];

            fibs[0] = 0;
            fibs[1] = 1;
            int sum = 1;

            for (int i = 2; i < numFibs; i++)
            {
                fibs[i] = fibs[i - 1] + fibs[i - 2];
                sum += fibs[i];
            }

            return sum;
        }

You must also use the out keyword when calling the method.

            int[] myFibs;
            int sum = FindFibsThrough(10, out myFibs);

774-001

#772 – Initializing an Array as Part of a Method Call

When you want to pass an array to a method, you could first declare the array and then pass the array by name to the method.

Suppose that you have a Dog method that looks like this:

        public void DoBarks(string[] barkSounds)
        {
            foreach (string s in barkSounds)
                Console.WriteLine(s);
        }

You can declare the array and pass it to the method:

            Dog d = new Dog();

            // Declare array and then pass
            string[] set1 = { "Woof", "Rowf" };
            d.DoBarks(set1);

Or you can just initialize a new array instance as part of the method call, without first declaring it:

            // Initialize and pass array without declaring
            d.DoBarks(new string[] { "Grr", "Ack-ack" });

You can also initialize a multi-dimensional array as part of a method call:

            // Initialize and pass multi-dimensional array
            d.AddNumbers(new int[,] { { 1, 2, 3 }, { 9, 10, 11 }, { 100, 12, 32 } });

772-001

#760 – Adding New Class Members from a Class Diagram

In addition to adding new types from a class diagram within Visual Studio, you can also add members to existing types.

In the class diagram, you right-click the top area of the class and then click Add in the popup menu.  You’ll see a list of the different class members that you can add.

760-001

For example, we can add a RollOver method to the Dog class.  After selecting Method from the menu, a new method shows up in the list of methods for the class.

760-002

After you name the new method, different attributes of the method will show up in the Properties window on the right side of the Visual Studio workspace.  You can then make changes to the method by changing its properties.

760-003

You can of course go view or edit the new method in the code editor window.

760-004