1

I am having a problem in my code. I guess this is pretty straight forward, but I lack experience in OOP and C# so I have to ask you.

My code looks like this:

namespace RR
{
    static class Program
    {
        [STAThread]

        private static string token;

        static void Main()
        {
            [...]
        }
    }
}

The problem is that the variable token is not working/won't compile. I guess the error is pretty easy to spot, but I've tried any versions of static, public static and using functions (setters and getters) to do the work, but nothing works. I found this: Global variable in a static method , but then I had to remove [STAThread] which I have no clue what even does, so I'd rather cross this problem another way.

The source is auto-setup when I created a new project in C# 2012.

To clearify: How can I use public variables in a static class like this without having to remove STAThread?

Community
  • 1
  • 1
OptimusCrime
  • 14,662
  • 13
  • 58
  • 96

2 Answers2

6

[stathread] is an attribute and relates to the code directly below it - put it back above the main function where it was originally and put your variable above it and you'll be fine

and you are correct that you need to declare you variable with the static keyword as you suggested

user1727088
  • 159
  • 4
  • Thank you sir! You were right, moving the `main` right under `stathread` fixed the problem and static variables worked like I found on the internetz. I'll accept in 4 minutes :) – OptimusCrime Oct 07 '12 at 22:33
  • @L.B : It's correct (for starters...). I though the problem was something else, but using static variables in the static class worked. The problem was that stathread was before this and it screwed things up. – OptimusCrime Oct 07 '12 at 22:34
  • @OptimusCrime but this answer doesn't say anything about instance variables in static classes. Moving `STAThread` attribute in your class isn't enough as you already noticed. – L.B Oct 07 '12 at 22:37
  • @L.B : No, but combined with `private static string token;` as I wrote in the first post, it works like a charm. – OptimusCrime Oct 07 '12 at 22:39
  • @L.B - I thought he'd already solved the static but I've clarified above – user1727088 Oct 07 '12 at 22:39
1

[STAThread] is an attribute for a method. It will need to remain just before static void Main() It's generally a best practice not to have business logic inside of your entry point, but instead create new instances of your worker classes from within the Main().

If you want it to compile, move [STAThread] to just above static void Main() and change private static string token;

Middas
  • 1,862
  • 1
  • 29
  • 44