XenoPuTtSs
XenoPuTtSs

Reputation: 1284

c# have compiler computer value of constant

I'm having a hard to trying to figure out if this is possible when I really don't even know what is called.

I have a APIKey (which can change with different builds) and we have another field that converts that APIKey to be more web friendly. It is the web friendly on that I would like to have the compiler calculate.

Currently we are recalculating the value every call to the webapi. I could easily just define a const and put in the webfriendly version of it, but I want to be a little fancier and offer less maintenance.

what I want is something like this.

public class WebSearch{
  private const string ApiKey="jsdfjsd90234092j3_%sss";
  private const string WebFriendlyKey=#Compiler(ApiKey.Replace("-","+"));
}

Where WebFriendlyKey is computed by the compiler.

Upvotes: 0

Views: 430

Answers (2)

Eric Lippert
Eric Lippert

Reputation: 660573

Section 7.19 of the C# 4 specification lists every operation that the compiler will perform on constants on your behalf. String replacement is not one of them.

You can however use a readonly static field, or a readonly static field with a static property that computes the value if it is not already computed and fetches the value if it is. The compiler will not do the compilation in that case, but the computation will only be performed once per appdomain.

That said, I agree with Henk. You have bigger fish to fry here. Worry about something that is actually impacting correctness or performance.

Upvotes: 8

Chris Shain
Chris Shain

Reputation: 51344

I do not believe that the current C# compiler can do this. Maybe with the new modular compiler coming out (Roslyn).

What you can do right now is calculate the WebFriendlyKey just once each time your process starts, and store that for the lifetime of the process, which I assure you is just about as good as a constant from a performance perspective:

public class WebSearch{
  private const string ApiKey="jsdfjsd90234092j3_%sss";

  // This guy will only run once per AppDomain
  private static readonly string WebFriendlyKey = ApiKey.Replace("-","+");
}

Upvotes: 3

Related Questions