Tommy Naidich
Tommy Naidich

Reputation: 762

Class With The Same Name Already Exists

I've created a class named "Group" in my .NET C# web-application.

When I try to access this class within other classes I get into no troubles, however, in certain points within my code when I try to access the very same class, it refers me to a different built-in class named "Group" too under the the lib. Regular Expressions.

My question: How can I specify directly that I am trying to access a different class? If there were 2 classes under different libs. named the same way, I would of just typed X.Group and Y.Group in order to specify the difference, but I'm not sure what I need to type in order to access my manually created class within my code.

EDIT: I have no namespace for my web-application as far as I know. I am using WebForms in order to develop my website, hence no namespace is created as far as I'm concerned.

Thanks in advance.

Upvotes: 1

Views: 1823

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500145

How can I specify directly that I am trying to access a different class

You could:

  • Use the fully-qualified name, e.g.

    MyNamespace.Group x = new MyNamespace.Group();
    
  • Avoid adding a using directive for System.Text.RegularExpressions unless you really need it (maybe fully-qualifying uses of that instead)
  • Use an alias via a using directive:

    using MyGroup = MyNamespace.Group;
    ...
    MyGroup x = new MyGroup();
    

If you don't have a namespace declaration, you can just refer to global::Group instead of MyNamespace.Group... but I suspect you do have a namespace, and I'd urge you to create one if you don't already have one.

Upvotes: 2

Peter Duniho
Peter Duniho

Reputation: 70652

The first layer of protection against this problem is to be careful about giving your types such general names. That's the best solution.

Barring that, then you can do one of two things:

  • Fully qualify the type name where you use it. E.g. MyNamespace.Group
  • Declare a type alias via using. E.g. using MySpecialGroup = MyNamespace.Group;

Upvotes: 2

user2160375
user2160375

Reputation:

You can use using directive:

using Group = X.Group;

var group = new Group(); \\ default Group class comes from X namespace;
var group2 = new Y.Group();  \\ if  you want other class, specify full namespace.

Upvotes: 1

Matten
Matten

Reputation: 17631

If you only want to access your own class in the code, you can create an alias for it with the using keyword:

using Group = My.Namespace.Group;

(at the top of your class, besides the normal using directives).

Otherwise it's always possible to use the fully qualified name in the code

var Group = new My.Namespace.Group;

Upvotes: 0

Related Questions