All,

I am pulling my hair out with this. I need to make a constant String avaiable to all classes in my program and I can't figure out how to do it. This is a simple console app...

I've tried the obvious, public static const myString = "whatever"; but I still get the dreaded error:

"The name 'myString' does not exist in the current context."

I made it public, how could it not exist? Is there anything more public than public?

Thanks,
Bill

When you use the variable precede it by the class name it's in. For instance, if the your main form is Form1, you'd use it, Form1.MyVariable.

In C#, everything belongs to something. In the case of static variables, they belong to the class. So you must (as tinstaafl said) proceed them with the class name (basically, we won't go into using and things now). Non-static variable belong to instances of classes, so you proceed them with the variable.

class Sample {
    static const Int32 MyConstant = 4;
    int const Int32 myInstanceConst = 5;


    void SomeMethod() {
        int a = 2 * Sample.MyConstant; // class constant
        int b = this.myInstanceConst;  // instance constant
    }
}

Now there is a different issue with the use of 'const', but I don't think you are creating a portable library so, again, we won't go into this issue.

Doh! Sorry about that... I should have known.

Thanks,
-Bill

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.