Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there constexpr like functionality/syntax (that can be used at compile-time in functions in C++) available in C#?

in C++, I can have a function (e.g. Fibonacci) like below:

constexpr int Fibonacci(int n) {
  //cout << "Executed Fib" << endl;
  switch (n) {
    case 0: return 0;
    case 1: return 1;
    default:
       return Fibonacci(n - 1) + Fibonacci(n - 2);
  }
}

and I can check in the main to ensure the function is correct by doing something like:
int main()
{
   static_assert(Fibonacci(5) == 7, "Bad Program");
   ///...
}


That means I do not have to wait till run time to evaluate if the Fibonacci function will work. It is like a simple test at a compile-time. I am asking if I can do thing kind of thing in C#.

What I have tried:

I google for this. Found that someone in quora mentioned java is missing this.
https://www.quora.com/What-is-the-counterpart-to-the-C++-constexpr-clause-in-languages-like-Java-or-C[^]
Posted
Updated 28-Jul-19 3:48am
v2
Comments
ZurdoDev 26-Jul-19 16:47pm    
c# has constants, but what exactly are you wanting to accomplish?
Benktesh Sharma 26-Jul-19 17:09pm    
in C++, I can have a function (e.g. Fibonacci) like below:

constexpr int Fibonacci(int n) {
//cout << "Executed Fib" << endl;
switch (n) {
case 0: return 0;
case 1: return 1;
default:
return Fibonacci(n - 1) + Fibonacci(n - 2);
}

}

and I can check in the main to ensure the function is correct by doing something like:

int main()
{
static_assert(Fibonacci(5) == 7, "Bad Program");
///...
}

That means I do not have to wait till run time to evaluate if the Fibonacci function will work. It is like a simple test at a compile-time. I am asking if I can do thing kind of thing in C#.
Patrice T 27-Jul-19 16:12pm    
Use Improve question to update your question.
So that everyone can pay attention to this information.
Benktesh Sharma 28-Jul-19 9:48am    
Thanks. I updated the question.

1 solution

No, there's nothing like that in C#. There is only a proposal for it: Proposal: Compile Time Function Execution · Issue #2379 · dotnet/csharplang · GitHub[^] but no implementation as of today.
 
Share this answer
 
Comments
Benktesh Sharma 27-Jul-19 9:42am    
Thanks Thomas Daniels

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900