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?
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.
The only advantage of extension methods is code readability.
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.
According to Microsoft, In fact, extension methods cannot access private variables in the type they are extending.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With