Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a runtime constant to be a compile time constant?

Tags:

c#

So I am working on a chemistry based project and ran into this tricky problem. I have a bunch of functions doing chemistry type calculations and want to pass avogadros number as a default parameter for a function. Let me just let the code talk:

class Constants 
{
    //must be readonly to b/c Math.Pow is calculated at run-time
    public static double readonly avogadrosNum = 6.022*Math.Pow(10,-22);
} 

class chemCalculations
{   //getting default parameter must be a compile-time constant
    public double genericCalc(double avogadrosNum = Constants.avogadrosNum);  
}

Edit: was unaware of exponential format, thanks guys

like image 315
user2202911 Avatar asked Feb 01 '14 17:02

user2202911


Video Answer


1 Answers

You can't, in general. Anything which involves a method call is not going to be a compile-time constant, as far as the compiler is concerned.

What you can do is express a double literal using scientific notation though:

public const double AvogadrosNumber = 6.022e-22;

So in this specific case you can write it with no loss of readability.

In other settings, so long as the type is one of the primitive types or decimal, you can just write out the constant as a literal, and use a comment to explain how you got it. For example:

// Math.Sqrt(Math.PI)
public const double SquareRootOfPi = 1.7724538509055159;

Note that even though method calls can't be used in constant expressions, other operators can. For example:

// This is fine
public const double PiSquared = Math.PI * Math.PI;

// This is invalid
public const double PiSquared = Math.Pow(Math.PI, 2);

See section 7.19 of the C# 5 specification for more details about what is allowed within a constant expression.

like image 78
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet