Click here to Skip to main content
14,302,071 members
Rate this:
Please Sign up or sign in to vote.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100