1

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?

  • 1
    Firstly, it absolutely kills readability, dont use in real project – caxapexac Mar 07 '19 at 11:03
  • 1
    You're better off not nesting them and using a prefix/suffix e.g SpaceMineAbility. Nested classes besides the occasional struct will give you hours of headache a month down the line – Prodigle Mar 07 '19 at 11:07
  • can you be more specific about how it kills readability and can cause headache? to me, it looks much more organized and makes much more sense. – Agent Tatsu Mar 10 '19 at 17:49

2 Answers2

2

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
            }
        }
    }
}
caxapexac
  • 781
  • 9
  • 24
  • Ah, I see. If I'm not mistaken, isn't there a `global` namespace that all classes not in a namespace default to? I tried that but it the compiler didn't seem to understand what I wanted to do. – Agent Tatsu Mar 07 '19 at 11:30
  • @AgentTatsu yes, there is global namespace (https://stackoverflow.com/questions/25491518/what-namespace-will-a-class-have-if-no-namespace-is-defined) but it's not a good practice - you should use namespaces everywhere to not lose your work ;) – caxapexac Mar 07 '19 at 11:32
0

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.

NibblyPig
  • 51,118
  • 72
  • 200
  • 356