59

In Java I can write:

public final static MyClass foo = new MyClass("foo");

Is there any equivalent in C#?

shA.t
  • 16,580
  • 5
  • 54
  • 111
peter.murray.rust
  • 37,407
  • 44
  • 153
  • 217

2 Answers2

93

The closest thing (not exactly the same, final has other meanings too) for Java final fields I can think of is readonly:

public static readonly MyClass field = new MyClass("foo");

If you have a primitive type (string, int, boolean), you may want to use const instead.

public const string MAGIC_STRING = "Foo";
Snekse
  • 15,474
  • 10
  • 62
  • 77
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 7
    For fields, they're *almost* exactly the same thing. There are different rules around initialization (irrelevant here) and for some times `final` fields in Java act like `const` fields in C#, but in this case I think they're effectively equivalent. – Jon Skeet Jul 25 '09 at 09:47
  • 3
    Be aware of the difference between `readonly` and `const` though. `const` bakes in the value, so if you swap out a DLL with a `const` value in it, other DLLs consuming that one will need a rebuild to get the new value. `readonly` is runtime and will not require this. – Nick Gotch May 13 '14 at 15:45
  • So we don't need "static" for the primitive type? – Chandler Apr 17 '18 at 21:18
-5
sealed class finalClass
{
   ...
}
Steve
  • 11,831
  • 14
  • 51
  • 63