ExpertLoser
ExpertLoser

Reputation: 257

Namespace scope in C#

Does the name of namespace also define the scope in the class?

  1. For example, I have namespace that is named by solution by default. Lets say in Program.cs name of namespace is "MySolution".
  2. in the next file interface that I have created, name of namespace is "Interfaces"

When I go back to class, to implement this interface, it was not in the scope (I could not find it in intellisense). So if class has one namespace, and interface has second namespace, than I cant use it in my class. I thought namespace is only used to organise classes (like a surname), but I guess it also defines a scope.

Upvotes: 4

Views: 2688

Answers (1)

Brandon O'Dell
Brandon O'Dell

Reputation: 1171

"The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types." https://msdn.microsoft.com/en-us/library/z2kcy19k.aspx

To use a class, interface, struct, enum, delegate from another namespace, you will need to use the fully qualified name of the type, or declare a reference to that namespace with using Interface; at the top of your class. IE:

using Interfaces;  //can reference namespaces here

namespace MySolution
{
    public class Program 
    {
        //or you can use the fully qualified name of the type
        public Program(Interfaces.MyInterface example) 
        {

        }
    }
}

Upvotes: 5

Related Questions