ehh
ehh

Reputation: 3480

Compiler complaining on a missing namespace which is the name of the class

I have the following:

// Generator.cs
namespace MRP
{
    public class Generator
    {
        public enum ModeGeneration
        {
            ByRequest,
            ByCommit
        }
    }
}

// CustomerOrderWrapper.cs
namespace MRP
{
    class CustomerOrderWrapper
    {
        readonly ModeGeneration _mode;
    }
}

Why am I getting an error that the namespace name 'ModeGeneration' could not be found. Both classes are under MRP namespace, why the compiler is complaining on 'ModeGeneration' namespace?

Upvotes: 0

Views: 83

Answers (4)

Roman
Roman

Reputation: 259

Yes they are in the same namespace, but enum ModeGeneration is also inside Generator class. So either:

  • Put the enum outside the Generator class and use it as you have

or

  • Prefix ModeGeneration in CustomerOrderWrapper.cs with Generator - Generator.ModeGeneration

Upvotes: 1

Tien Nguyen Ngoc
Tien Nguyen Ngoc

Reputation: 1555

There are two method to solve this problem

Method 1) You can use class name put in front of enum

namespace MRP
{
    public class Generator
    {
        public enum ModeGeneration
        {
            ByRequest,
            ByCommit
        }
    }
}

// CustomerOrderWrapper.cs
namespace MRP
{
    class CustomerOrderWrapper
    {
        readonly Generator.ModeGeneration _mode;
    }
}

Method 2) You can bring enum from in class to out namespace

namespace MRP
{
public enum ModeGeneration
        {
            ByRequest,
            ByCommit
        }
    public class Generator
    {

    }
}

// CustomerOrderWrapper.cs
namespace MRP
{
    class CustomerOrderWrapper
    {
        readonly ModeGeneration _mode;
    }
}

I hope it will help you.

Upvotes: 1

Abhishek
Abhishek

Reputation: 2945

That is because your enum is defined in the class. Change the code as follows:

namespace MRP
{
    class CustomerOrderWrapper
    {
        readonly Generator.ModeGeneration _mode;
    }
}

Upvotes: 1

Cheng Chen
Cheng Chen

Reputation: 43523

Read the error message again. It should say something like "can't find class or namespace ModeGeneration", and it's correct, there is no class/namespace named ModeGeneration, maybe you want Generator.ModeGeneration?

As an inner class, Generator.ModeGeneration is the whole type name, and you can't omit the outer class name, because you can define a few inner classes with the same name in C# like this:

namespace Foo
{
    class One
    {
        public class Bar { }
    }

    class Another
    {
        public class Bar { }
    }
}

You can see Bar is ambiguous. You should use One.Bar and Another.Bar instead.

Upvotes: 2

Related Questions