How to Disambiguate Between External Class and Nested Class

64 Views Asked by At

I have a situation in which one of my classes is called SpaceMine, and another class I have is called Ability and has a class nested within it called SpaceMine:

public class SpaceMine
{

}

public class Ability
{
    public class SpaceMine :  Ability
    {
        void Foo()
        {
            SpaceMine spaceMine;
        }
    }
}

Within Foo(), I'm trying to declare a variable of type SpaceMine (not Ability.SpaceMine), but it keeps saying that my variable is of type Ability.SpaceMine. Aside from changing the names, how can I ensure that the compiler knows which type I'm trying to declare?

2

There are 2 best solutions below

2
caxapexac On BEST ANSWER

Use explicit declaration

namespace SpaceName
{
    public class SpaceMine
    {

    }

    public class Ability
    {
        public class SpaceMine :  Ability
        {
            void Foo()
            {
                Ability.SpaceMine nestedMine; //Nested
                //Ability is reducant but it improves readability a little
                SpaceName.SpaceMine globalMine; //Not nested
            }
        }
    }
}
0
NibblyPig On

I expect you'd simply have to use the full path.

I assume SpaceMine is inside a Namespace - and if it's not, you need to wrap the entire file in a namespace.

Then you can do new YourNamespace.SpaceMine(); to get the parent one, or new YourNamespace.Ability.SpaceMine() to access the nested one.

I wouldn't recommend doing this though as the readability is severely impacted.