simple question :-
i have the following simple if (..) statements :-
if (foo == Animal.Cat || foo == Animal.Dog)
{ .. }
if (baa == 1|| baa == 69)
{ .. }
is it possible to refactor these into something like ...
DISCLAIMER: I know this doesn't compile .. but this is sorta what i'm trying to get...
if (foo == (Animal.Cat || Animal.Dog))
{ .. }
if (baa == (1 || 69))
{ .. }
Cheers :)
I wonder if a lambda expression extension could do this? :P
Refactoring in C#. To accomplish any functionality in an… | by ParTech | CodeX | Medium To accomplish any functionality in an application, every developer has a unique style. Some of them write effective and less complex codes while some write more complex ones.
However, if a codebase ever needs to be inspected or updated, whether it’s being extended, improved to keep up with changes to the language, or even just reviewed to audit the efficiency, then code refactoring is more a necessity than just a nice thing to do.
While we refactor, we figure out that the code is tightly coupled and needs to be refactored to a loosely coupled code. To do so, an interface has to be created which will be inherited by the class. Since the class has a lot of methods, you have to make it easier to create the interface with all the methods.
Refactoring is the process of improving the performance, readability, and complexity of the code by altering its internal structure and external behavior. In other words, it is an efficient technique for cleaning up the code in a controlled manner. Refactor is not rewriting the code, as the crux of the code (i.e functionality) remains the same.
I usually create an extension method called IsIn()
that takes a generic parameter array of type <T>
and then calls .Contains()
on it, passing the instance on which the extension is called.
It looks like if (foo.IsIn(foo1, foo2))
. Very simple to write, super easy to use.
It's not much use in this specific case where you only have two options, but if there could be many options you might prefer to put the options in a list and then use Contains
like this:
List<Animal> allowedAnimals = new List<Animal>
{
Animal.Cat,
Animal.Dog,
Animal.Fish,
Animal.Frog,
Animal.Horse
};
if (allowedAnimals.Contains(animal))
{
// etc...
}
This method will also work on other types than enums
including types that you cannot switch
on. It is also useful if the list of allowed values will only be known at runtime.
Note that if you create a new list each time there will be a performance penalty.
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