Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# assign const member with function

Tags:

java

c#

in java its possible to do something like this

class {
    final int x = Random.randomInt();
    final int y = Random.randomInt();
}

...

switch (intVariable)
{
    case x: break;
    case y: break;
}

as long as generateInt is final, this compiles.

is there an equivalent in C#?

edit: you might ask why i dont use concrete values or enums, but i have my reasons why the values are be random. ;)

like image 273
clamp Avatar asked Apr 11 '26 06:04

clamp


1 Answers

with const you can't do that, it has to be a compile time constant.

You may use readonly, something like:

public class yourClass
    {
        public readonly int x = generateInt();

        public static int generateInt()
        {
            return DateTime.Now.Millisecond; // or any other method getSomeInt();
        }
    }

EDIT: Since the question is now edited and asks with reference to case expression in switch statement. You can't specify a variable or readonly in the case statement, it has to be constant expression/compile time constant.

From MSDN - Switch

Each case label specifies a constant value.

You may use if...else for your scenario.

like image 164
Habib Avatar answered Apr 13 '26 20:04

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!