Scoping Usings
July 13, 2009 at 3:12 PM
—
alex
Consider the following code, which results into an error when Figure class is an ambiguous reference to either N1 or N2 namespace:
using System;
using N1;
using N2;
namespace N1
{
class Figure
{
public void Method()
{
Console.WriteLine("N1::Figure.Method");
}
}
}
namespace N2
{
class Figure
{
public void Method()
{
Console.WriteLine("N2::Figure.Method");
}
}
}
namespace ConsumeUsing
{
class Program
{
static void Main(string[] args)
{
Figure f = new Figure(); // Error, Figure is an ambiguous reference.
f.Method();
}
}
}
To resolve this, you can rewriter the using statements, and, if you want to use Figure from the namespace N2, add using N2 statement inside the ConsumeUsing scope as follows:
using System;
using N1;
namespace N1
{
class Figure
{
public void Method()
{
Console.WriteLine("N1::Figure.Method");
}
}
}
namespace N2
{
class Figure
{
public void Method()
{
Console.WriteLine("N2::Figure.Method");
}
}
}
namespace ConsumeUsing
{
using N2;
class Program
{
static void Main(string[] args)
{
Figure f = new Figure();
f.Method();
}
}
}
This will tell to compiler to, first, look at N2 classes for the candidates, then, at the outer usings.
5e594892-d8f9-46d7-a46d-5b782f942410|0|.0
Posted in:
Tags: programming