Static/Instance methods and extension questions

I'm new to C# and I began working on a project that needed a method added to a class in C#. I found myself re examining the differences between static and instance methods and I'm unable to explain the following in a sample project.

My Core object:

namespace ExtendingObjects
{
    public class MyCoreObject
    {
        public String name;
        public String returnName()
        {
            return name;
        }
    }
}

My attempt to extend the object:

namespace ExtendingObjects
{
    public static class Extensions
    {
        public static void addName(this MyCoreObject mco, String str)
        {
            mco.name=str;
        }

        public static String getName(this MyCoreObject mco)
        {
            return "test";
        }
    }
}

Calling program:

namespace ExtendingObjects
{
    class Program
    {
        static void Main(string[] args)
        {
            MyCoreObject co = new MyCoreObject();
            co.addName("test");
            //Static method seems to work with instance?
            String n = co.returnName();
            Console.WriteLine("The name is " + n);
            Console.ReadLine();
            //Does not work
            //Static method from a type
            //String n2 = MyCoreObject.getName()
        }
    }
}

It was my understanding that static items stayed with the class and instance items with the instance per MSDN Static and Instance Members. However, I seem to be able to access a static method through an instance above, but not able to access a static method through a type.

Why does co.returnName() work and not MyCoreObject.getName()? I would think they would be reverse based on my reading. How can I make the getName() method available without instantiating the object first?

Thanks in advance.

Jon Skeet
people
quotationmark

Your two methods are extension methods, which are meant to look like instance methods when they're called. They can be called statically, but you need to supply the instance as the first argument, and specify the class which declares the extension method, not the type that the method "extends":

Extensions.getName(co);

When you call an extension method "as" an instance method, it's just a compiler trick. So this code:

co.addName("test");

is compiled to the exact equivalent of:

Extensions.addName(co, "test");

(As an aside, you would do well to start following normal .NET naming conventions as soon as possible. The earlier you get in the habit, the better.)

people

See more on this question at Stackoverflow