I have:
- Main Program Class – uses Library A
- Library A – has partial classes which mix in methods from Library B
- Library B – mix in methods & interfaces
Why would I need a using statement to LibaryB just to get their extension methods working in the main class? That is given that it’s Library B that defines the classes that will be extended.
EDIT – Except from code
// *** PROGRAM ***
using TopologyDAL;
using Topology; // *** THIS WAS NEEDED TO GET EXTN METHODS APPEARING ***
class Program
{
static void Main(string[] args)
{
var context = new Model1Container();
Node myNode; // ** trying to get myNode mixin methods to appear seems to need using line to point to Library B ***
}
}
// ** LIBRARY A
namespace TopologyDAL
{
public partial class Node
{
// Auto generated from EF
}
public partial class Node : INode<int> // to add extension methods from Library B
{
public int Key
}
}
// ** LIBRARY B
namespace ToplogyLibrary
{
public static class NodeExtns
{
public static void FromNodeMixin<T>(this INode<T> node) {
// XXXX
}
}
public interface INode<T>
{
// Properties
T Key { get; }
// Methods
}
}
This is an unfortunate discoverability issue with extension methods. In order to make them available you need to add a
usingstatement for the namespace containing the static class that has the extensions. Check out this blog about extension methods.Here is some background on extension methods:
My understanding is that using extension methods is just like using any other type, except that you can’t qualify them (that is just syntactically impossible), hence the need for
usingstatement. Since you can define multiple of them in different classes in different namespaces, the compiler needs a way to resolve ambiguity.I envisage that in future Visual Studio will add a feature to import the right namespace when you type in the method name, in a similar way it does so for class and interface names.
Consider this scenario:
In order to use any of those extension methods you need to import the right namespace:
You might ask what happens when you import both namespaces. You get a compiler error just like this: