Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method as an Extension Method requires more reference than calling it directly

I have a extension method in what I will call HelperAssembly that looks similar to this:

public static class HelperClass
{
    public static void MyHelperMethod(this SomeClass some, OtherClass other)
    {
        // This object is defined in OtherAssembly1
        ObjectFromOtherAssembly1 object1 = new ObjectFromOtherAssembly1(some);

        // This object is defined in OtherAssembly2
        ObjectFromOtherAssembly2 object2 = new ObjectFromOtherAssembly2(other);

        DoStuffWith(object1, object2);    
    }
}

I have an assembly I will call CallerAssembly that has a reference to HelperAssembly.

My HelperAssembly has a reference to both OtherAssembly1 and OtherAssembly2.

SomeClass and OtherClass are both defineded in ReferenceAssembly. HelperAssembly and CallerAssembly have a reference to ReferenceAssembly.

Everything is great when I call my method from CallerAssembly like this:

HelperClass.MyHelperMethod(some, other);

However, I get build errors when I call it like this (as an extension method):

some.MyHelperMethod(other);

The errors say that CallerAssembly needs to reference OtherAssembly1 and OtherAssembly2.

I am confused. I thought that extension method syntax was just syntactical sugar, but did not actually change the way that things compiled.

I do not want to add the references that it is suggesting so I will not make the call as an Extension Method. But I would like to understand what the difference is.

Why does calling the method directly build fine but calling it as an Extension Method fail to build?

like image 527
Vaccano Avatar asked Dec 07 '11 17:12

Vaccano


People also ask

How do you call an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

What is an advantage of using extension methods?

The only advantage of extension methods is code readability.

How does extension method work?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Can extension methods access private methods?

According to Microsoft, In fact, extension methods cannot access private variables in the type they are extending.


1 Answers

Any chance that CallerAssembly targets the .NET Framework Client profile and HelperAssembly targets the "full" .NET Framework?

I've run into problems with Extension methods (and other things) when I've done this.

like image 68
0xfded Avatar answered Oct 13 '22 05:10

0xfded