clamp
clamp

Reputation: 34006

C# assign const member with function

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. ;)

Upvotes: 3

Views: 779

Answers (1)

Habib
Habib

Reputation: 223247

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.

Upvotes: 6

Related Questions