C# Best Practices – Is Having Public Constants Bad?

c

Is this:

public MyClass
{
    public const string SomeString = "SomeValue";
}

worse than this:

public MyClass
{
    public static string SomeString { get{ return "SomeValue";}}
}

Both can be referenced the same way:

if (someString == MyClass.SomeString)
     ...

The second however, has the protection of being a property. But really how much better is this than a const?

I have learned over and over the perils of having public fields. So when I saw some code using these constants on public fields, I immediately set about refactoring them to properties. But halfway through, I got to wondering what benefit it was to have the static properties over the constants.

Any ideas?

Best Answer

In C# it's very bad for none of the reasons mentioned in this thread.

Public constants in C# get baked into referencing assemblies. Meaning, if you have a SomeOtherClass in a separate assembly referencing SomeString in MyClass, the CIL generated for SomeOtherClass will contain a hardcoded "SomeValue" string.

If you go to redeploy the dll that contains MyClass but not SomeOtherClass and change the const, SomeOtherClass won't contain what you think it will--it will contain the original value.

If you're 100% positive it's a universal constant like Pi, go crazy; otherwise tread carefully.

Here's a better explanation : https://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly