There are a lot of IF statements here
Is there a different way of doing all these operations and not use all the if statements? like maybe a switch case or something.
18 Replies
Nested if blocks can be removed. You can check two conditions with a single if. In the form of if (a && b), there is only one if condition in it, no separate situation is handled. The switch-case structure may be more suitable for such a situation.
You can even write a generic method to evaluate relevant conditions rather than repeating the same code. CheckIsNull(SmokeFix) etc.
?? and ??= operators - null-coalescing operators - C#
The
??
and ??=
operators are the C# null-coalescing operators. They return the value of the left-hand operand if it isn't null. Otherwise, they return the value of the right-hand operandyou can review this article for null-coalescing. Its useful
To aggregate the data you would need to know the definition of blocks. If each block is its own type such as frictionblocks being a list of FrictionBlock, you could instead write an abstract or virtual method in the base, override it with the null component check specific to the derived and then replace all of the if statements with a single for loop that just calls the method on base type
@DaVinki would using an abstract method be good here though?
I dont actually think i can get into the blocks themselves
You could make a method that handles the identical cases of checking a list and adding the component if null, that would reduce each of those cases to a single, readable line.
theres also this but i wont worry about it till later
Yeah, abstract and virtual methods are used to do things without needing to know the implementation details. You wouldn’t need to know how it adds a missing component, just that it does and works for every type inheriting the base type declaring the method
Ive never actually worked with abstract/virtual methods, could you give me a rundown and a push in the right direction?
MSDN will have a lot of documentation over inheritance. Also for the switch cases, values have to be mapped somewhere somehow. In code, in some variable file, wherever
If it ain’t mathin, it’s manually mappin
Inheritance in C# - C#
Learn to use inheritance in C# libraries and applications.
Just fyi you’ll write one method for each if statement involving the block name if you do it this way
that was the issue i was trying to solve
Right it just wouldn’t be a load of if statements. It’d be structured and could be done for any single instance if needed, then you would just need a foreach loop and call the overridden method
That generic method is another way of doing it but you’ll be calling it for every type still
are these the same things?
Yes of course but I do not know what type your
block
has, so I named it TypeOfBlock
janderedev 2.0