Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
like image 929
jpavlov Avatar asked Nov 22 '25 16:11

jpavlov


1 Answers

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.

like image 199
Paul Sasik Avatar answered Nov 24 '25 06:11

Paul Sasik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!