-1

First of all I would like to apologize for such primitive question but I'm a complete beginner and I wasn't able to find a solution that I would understand.

I'm learning C# (because of Unity) and I wanted to experiment a bit and create a little program by myself. But after coding in "Basic" Visual Studio instead of "Unity" Visual Studio, I've stumbled on problem I couldn't fix nor understand.

string hello = "Hello, World!";

static void Main()
{
    otherMethod();
}

void otherMethod()
{
    Console.WriteLine(hello);
}

On Unity I could do this without problem because the Start method allowed non-static methods inside of it but now...

...if I change remove static from Main method the program won't run.

...if I add static to the otherMethod, the otherMethod won't be able to access the string hello.

I know this is primitive and that in the code above I could simply fix it by putting string hello inside the otherMethod (etc.) but this was just an example.

If I had to have string hello outside of the methods and use the otherMethod inside the Main method, how could I achieve it? Is it possible or am I doing it completely wrong?

  • 1
    Possible duplicate of [Static vs non-static class members](https://stackoverflow.com/questions/9924223/static-vs-non-static-class-members) – Cid May 03 '19 at 14:35
  • 1
    Main should be static, you need an entry point to your program. Take a look at the [C# language specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/introduction) – Luthfi May 03 '19 at 14:36
  • Make `otherMethod()` static as well as `hello` field: `static void otherMethod()`, `static string hello = ...` – Roman May 03 '19 at 14:37
  • 1
    It is not a static method so you need to create an instance of the class. That merely takes var prog = new Program(); prog.otherMethod(); – Hans Passant May 03 '19 at 14:39

2 Answers2

2

You can't call non-static methods from a static method. You first need to instantiate the class then you can call the methods. Working Example of your code:

 class Program
{
    string hello = "Hello, World!";
    static void Main(string[] args)
    {
        var test = new Program();
        test.OtherMethod();
    }

    void OtherMethod()
    {
        Console.WriteLine(hello);
    }
}

Here is a decent article on static vs non-static https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231

Psychoboy
  • 308
  • 1
  • 3
  • 10
0

Did you try making your variable static?

        public static string hello = "hello";

This is probably not the 'Correct' way to accomplish this but you should be able to brute force it.