How to make an expression as short as possible
To any min maxxers out there, i am trying to shrink these few lines to inhuman extremes for.. no reason really. GetEffectsOfType(uint type, int baseValue) returns the total value of effects of type "type" or null if it finds none. I want "value" to remain null if there were no effects found in the entire foreach, otherwise it has to have the total value. This code works, i was just thinking if there was a way to go smaller, maybe making more use of the null coalition operator ??.
27 Replies
why value is nullable ?
that force you to use the null collasing operator
i want to distinguish between "no effects were found" and "there were effects, but with a value of 0"
you can probably do it using aggregate ? 🤔
if you know how it works
so uhh, fun fact, i do not 👍
i kinda just looked over the microsoft csharp tutorials a little and combined my highschool knowledge of c++to make this work
can't u just do
and remove the if and value ??= 0
all together
if value starts as null then it won't do anything
it will be just 0
null + 0 is null
no
where do u declare value
ah I see
up at the top
int? value = null;
just set value to 0 instead of null
you're doing that inside
is 0 an effect?
again, i want to distinguish between "i found effects with a value of 0" and "nothing was found"
ah ok there is an effect with 0
yeah
You shouldn't use a nullable primitive to represent a special state in the first place.
Use an enum or wrap it some other way.
But null having a special meaning, beyond it just being missing, is not good practice.
well, doesn't it mean missing here? there were no effects, so there's no value to get from them.
but i get what you mean
he means in the sense u could have instead -1 representing non-existing as oppose to null for example
well i can have values of -1
so no can do
that was just an example
but that wouldn't change the situation either
yeah, but i still think null works best here
i'm just gonna keep using this then
it's not broken nor that inefficient, really
You can also use the Try Pattern with an out parameter instead of calling the (possibly maybe expensive, who knows) method twice.
I really like the try pattern
isn't try used for exceptions? how would i implement it here?
No TryParse not a trx block.
also, here's the method, i'll let you judge how expensive it is [Effects has no more than 3 or 4 members and usually it's just one]
i'm gonna have to look into that lol
Just take a look at the implementation of int.TryParse