Search code examples
c#access-modifiers

accessing objects from a class


I have created a seperate .cs file names aNameClass.cs and have stored the following class in it. I am able to iniatiate it in my Main() statment, but when I try to access the GetChoice object, it tells me it is inaccesable due to invalid prividlidges.

here is my code to iniatiate it and access it.

namespace aNameCollector
{
// ...

csGetChoice gc = new csGetChoice();
choice = gc.GetChoice();   //invalid prividlidges???


    class csGetChoice
    {
        static string GetChoice()
        {
            string choice = " ";
            Console.WriteLine("++++++++++++++++++=A Name Collector+++++++++++++++");
            Console.WriteLine();
            Console.WriteLine("What would you like to do?");
            Console.WriteLine("E = Enter a Name || D = Delete a Name || C = Clear Collector || V = View Collector || Q = Quit");
            choice = Console.ReadLine();
          return choice;
        }
    }

Solution

  • You need to use a static reference and specify public for the method like this:

    // static access:
    choice = csGetChoice.GetChoice(); 
    ...
    public static string GetChoice() { ...
    

    or make the method an instance method instead of static and define and access it like this:

    // instance access:
    csGetChoice gc = new csGetChoice();
    choice = gc.GetChoice();  
    ...
    public string GetChoice() { ... // static keyword removed
    

    If you don't provide an access modifier the default is private and therefore visible only to the class that contains it and not to any other classes.