2

I tried to access in my Test.cs to strings in my other class TerminalStrings.cs but was not able.... how can I access to them ?

TerminalStrings.cs :

namespace RFID_App
{
    class TerminalStrings
    {
        public static readonly string identiError = "ERROR";
        public const string identiSuccess = "SUCCESS";
    }
}

In Test.cs:

 namespace RFID_App
    {
          class Test
        {
            public Test()
            {
               string test;
               TerminalStrings stringlist = new TerminalStrings();
               test = stringlist.identiError; //this was not possible 
            }
        }
    }
Samy
  • 1,013
  • 3
  • 15
  • 25

3 Answers3

7

const are implicitly static, you can't access them with instance member instead you need the class name to access.

test = TerminalStrings.identiError;

See: Why can't I use static and const together? - By Jon Skeet

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Is there a difference when I use "static readonly" or "const string" – Samy May 21 '14 at 17:12
  • [Yes.](http://stackoverflow.com/q/755685/781792) Using `const` means that code will hardcode it at compile-time. Only do this for things that can never, ever even theoretically change, like `PI`. – Tim S. May 21 '14 at 17:13
  • I wouldn't even use it for Pi due to the fact that it cannot be exactly represented with floating point numbers, so you'll find different values for Pi through-out different programs and you might want to change it later. I'd only use it for values that will never change and the exact value can be stored. 'Seconds in a day', 'feet in a mile', etc. – LVBen May 21 '14 at 17:23
2

The consts are not member variables, they are on the class.

string test = TerminalStrings.identiError;
krillgar
  • 12,596
  • 6
  • 50
  • 86
1

Constants in C# are automatically static. They're not part of the data of an instance, but of the class itself - after all, stringlist and stringlist2 don't have different copies.

So to access it, access TerminalStrings.identiError:

public Test()
{
   string test;
   test= TerminalStrings.identiError;
}
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63