C# class name - method name collision

2.4k views Asked by At

Say I have a class named 'Foo', with some static member, and in some other class (which is under the same namespace) there is a factory method with the same name, which uses this member:

namespace MyNamespace
{
    public class Foo
    {
        public static bool Invert = false;
        public int A {get; set;}
        ....
    }

    public class FooFactory
    {
        public Foo Foo(int A) 
        {
           if(Foo.Invert) // --> this gives the 'is a 'method', which is not valid in the   given context' Error
              return new Foo(-A);
           else
              return new Foo(A);
        }
    }
}

(Some code was omitted for brevity). Obviously, the compiler does not interprets the 'Foo' in the 'if' clause as the class 'Foo', but as the factory method. Assuming I'm not in liberty to change the class' name nor the factory method's name, can I force the compiler to recognize 'Foo' as a class name rather than the method name?

EDIT Sorry for not mentioning this earlier - both classes are in the same namespace, therefore MyNamespace.Foo.Invert does not do the trick.

2

There are 2 answers

1
Dejan Janjušević On BEST ANSWER

Your code does not work because what you actually try is to access MyNamespace.FooFactory.Foo method as if it was a class. If you specify MyNamespace.Foo you will specify the class which was intended.

namespace MyNamespace 
{ 
    public class Foo 
    { 
        public static bool Invert = false; 
        public int A {get; set;} 
        .... 
    } 

    public class FooFactory 
    { 
        public Foo Foo(int A)  
        { 
           if(MyNamespace.Foo.Invert)
              return new MyNamespace.Foo(-A); 
           else 
              return new MyNamespace.Foo(A); 
        } 
    } 
} 

This will work.

Concerning your EDIT, MyNamespace.FooFactory.Foo and MyNamespace.Foo are not the same.

1
user1096188 On

using directive to the rescue. Just create an alias for your class.

using FooClass = Namespace.Foo;

clicky