2

I have the following readonly string in my C# class.

private readonly string someString= "I am a string.";

I feel the urge to convert this to a const because the information is available at compile time. However, I have it as readonly because I am using it in a non-static context.

Is this the right thing to do? Or am I having an issue with my code design?

CookieEater
  • 2,237
  • 3
  • 29
  • 54
  • 2
    This ticket may help you : http://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly – SidAhmed Jan 27 '14 at 11:08
  • What makes you think that using a `const` in a non-static context is wrong? – Thomas Levesque Jan 27 '14 at 11:10
  • You have declared it as private, so it will be used only within the class you write. So keeping it as `const` is enough. Even `const` can be used in non-static context. – Karthik Kalyanasundaram Jan 27 '14 at 11:12
  • I am trying to use the variable in a non-static method and it is complaining to me that it cannot. – CookieEater Jan 27 '14 at 11:20
  • 1
    There's no reason you shouldn't be able to use that string from a non-static method. If you're getting a compiler error, *give us the compiler error*, otherwise we can't help you. – Chris Jan 27 '14 at 11:25

1 Answers1

11

I just figured out why. I was referring to the variable as this.someString. The error went away after I switched to MyClass.someString.

CookieEater
  • 2,237
  • 3
  • 29
  • 54
  • By the way, can anyone care to explain what difference this makes? – CookieEater Jan 27 '14 at 12:20
  • 1
    Constants are, in effect, always static, and as such aren't part of any instance. Therefore, you address them through the class and not through an instance. If you think about it, it doesn't make sense for constants to be instance-based - this.someString implies "the value of someString that belongs to this instance", which is misleading because it's exactly the same someString that all other instances have access to as well. – Chris Jan 27 '14 at 13:06