Question

I tried to implement a singleton class in the following way (I use VS2008 SP1) :

namespace firstNamespace
{
   class SingletonClass
   {
      private SingletonClass() {}

      public static readonly SingletonClass Instance = new SingletonClass();
   }
}

When I want to access it from a class in a different namespace (it seems that this is the problem, in the same namespace it works) like :

namespace secondNamespace
{
   ...
   firstNamespace.SingletonClass inst = firstNamespace.SingletonClass.Instance;
   ...
}

I get a compiler error:

error CS0122: 'firstNamespace.SingletonClass' is inaccessible due to its protection level

Does somebody have an idea how to solve this?

Many thanks in advance!

Was it helpful?

Solution

You're missing the keyword public from your class definition.

OTHER TIPS

Sounds more like the singleton is in a different assembly. The default modifier for a class is internal and thereby only accessible in the assembly.

The SingletonClass has internal visibility, so if the two namespaces are in different assemblies, the entire class in inaccessible.

Change

class SingletonClass

to

public class SingletonClass

change

class SingletonClass

to

public class SingletonClass

to mark it public, thus accessible

or even better:

public sealed class SingletonClass

since the members are static:

more here

You class SingletonClass is visible in other namespaces. But it is not visible in other Assemblies/Projects.

Your class is private. This means all code in your current project (=Assembly = .dll) can see this class. The class is however hidden for code in other projects.

There is a weak correlation between the namespace and the assembly. One namespace can exist in multiple assemblies, for example mscorlib.dll and System.dll both contain the System namespace.

But normally, when you create a new project in Visual Studio, you get a new namespace.

You can also add multiple namespaces to the one Assembly. This happens automatically in Visual Studio when you create a new folder.

You SingletonClass class is not public, so isn't visible outside the namespace assembly.

Correction: the comments are right, as says msdn:

Classes and structs that are not nested within other classes or structs can be either public or internal. A type declared as public is accessible by any other type. A type declared as internal is only accessible by types within the same assembly. Classes and structs are declared as internal by default unless the keyword public is added to the class definition, as in the previous example. Class or struct definitions can add the internal keyword to make their access level explicit. Access modifiers do not affect the class or struct itself — it always has access to itself and all of its own members.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top