views:

61

answers:

2

Hello,

I have a name space Company.Controls, which contains several controls. I also have a class called "Common" which contains enums/structures/static methods that I use throughout the controls.

Is there a way to make these "Common" peices belong to the Company.Controls namespace this way I don't have to keep typing "Common.Structure"? Essentially having he "Common" both a namespace and a class.

Just seems messy and confusing when reading the code.

example (all the other controls are in the Blah.Controls.Common namespace)

namespace Blah.Controls
{
    public enum ControlTouchState
    {
        Down = 0x00,
        Up = 0x01,
    }

    public Common()
    {
      //Stuff here
    }

}

Thanks.

+1  A: 

You can't get exactly what you want; in C# all methods have to be in a class.

Depending on what is in your Common class, you might be able to find something a slightly more satisfying by using extension methods:

namespace Blah.Controls
{
    public class CommonControl { }

    public static class Common
    {
        public static void Foo(this CommonControl cc) { }
    }

    public class Control1 : CommonControl
    {
        public void Bar()
        {
            this.Foo();
        }
    }
}

Another thing you might consider is using partial classes which would let you write simple wrappers elsewhere:

namespace Blop.Controls
{
    public static class Common
    {
        public static void Foo() { }
    }

    public partial class Control1
    {
        public void Bar()
        {
            Foo();
        }
    }

    public partial class Control1
    {
        public void Foo()
        {
            Common.Foo();
        }
    }
} 

Obviously, introducing some inheritence could eliminate some of the duplication; I'm assuming you don't want to do that.

Dan
A: 

Is there some reason that the nested types in Common MUST be nested? Why not separate them out into their own namespace?

namespace Common
{
    public struct Structure 
    {
        // ... 
    }

    public enum Enumeration
    {
        // ...
    }

    public class Common
    {
        // ...
    }
}

You could then use the Common namespace as such:

namespace Blah.Controls
{
    using Common;

    class Control
    {
        Struct myStruct;
        Enumeration myEnum;
        Common myCommon; // references the class, not the namespace
    }
}
jrista
As he said, the hard part is static methods in the *Common* class. He doesn't want to type `Common.Foo()` everywhere outside of the `Common` class.
Dan
He did not specifically target static methods as being the most difficult...he just mentioned structs, enums, and static methods equally. Obviously there is nothing that can be done about statics, however, creating the Common namespace means you don't need something like the following: Company.Controls.Common.Foo(new Company.Controls.Common.Struct { ... }, new Company.Controls.Common.Enumeration { ... });
jrista