badmaash
badmaash

Reputation: 4845

How do I construct local constants from values returned during runtime?

I want 'filename' to be constant:

string filename = "WR" + DateTime.Now.ToString("M_dd_yyyy") + ".xls";

I also want to keep filename as a local and not a field.(I know readonly can solve the problem that way)

Upvotes: 0

Views: 93

Answers (1)

Oded
Oded

Reputation: 499062

You can use a readonly variable. It can be initialized during declaration and changed in the constructor, but nowhere else. And, it only applies to fields, not local variables.

private readonly string filename = "WR" + DateTime.Now.ToString("M_dd_yyyy") + ".xls";

As for why you can't use a const this way - From MSDN:

A constant expression is an expression that can be fully evaluated at compile time.

And, of course DateTime.Now, can't be.

Upvotes: 3

Related Questions