Looking for a code optimization in c# that allows me to both define an enum and create a variable of that enum's type simultaniously:
Before:
enum State {State1, State2, State3};
State state = State.State1;
After (doesn't work):
enum State {State1, State2, State3} state;
state = State.State1;
Does anything like that exist?
There's no support for that in C#, but maybe you can workaround this and do something "near" to an enum by using tuples or anonymous types if you only need to switch some state and you don't need to do any special operations with it.
For example, using tuples, you can do this:
var someFakeEnum = Tuple.Create(0, 1);
C# 7 has introduced syntactic tuples:
var someFakeEnum = (State1: 0, State2: 1);
Or with anonymous types:
var someFakeEnum = new { State1 = 0, State2 = 1 };
And, after that, you can do something like:
int state = 0;
// If you're using tuples...
if(some condition)
{
state = someFakeEnum.Item2;
}
// ...or if you're using anonymous types or C# >= 7 tuples...
if(some condition)
{
state = someFakeEnum.State2;
}
Obviously this isn't an actual enumeration and you don't have the sugar that Enum type provides for you, but you can still use binary operators like OR, AND or conditionals like any other actual enumeration.
This is not an optimization.
No, nothing like that exists, and for good reason. It's much less readable and there's absolutely zero benefit to be gained in doing so. Declare them in two separate statements and be done with it.
If you're literally getting paid to reduce the number of lines in your source code, write it like this:
enum State {State1, State2, State 3}; State state = State.State1;
(Yes, that's a joke. Mostly.)
Switching from C/C++, I suppose?
No, can't do that
No, that doesnt exists. Nor is it very readable IMHO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With