I'm not sure why readonly
and const
didn't work for you since these are the keywords you need. You use const
if you have a literal (except for array literals) and readonly
otherwise:
public void f()
{
const int answer = 42;
}
private readonly int[] array = new int[] { 1, 2, 3, 4 };
private readonly DateTime date = DateTime.Now;
public void g()
{
Console.WriteLine(date.ToString());
}
readonly
only works on class level (that is, you can only apply it to fields). Also as a consequence of const
requiring a literal, it's inherently static while a readonly
field can be either static or instance.