Refactor method (C#) [duplicate] - c#

This question already has answers here:
Simply check for multiple statements C#
(2 answers)
C# - Prettier way to compare one value against multiple values in a single line of code [duplicate]
(2 answers)
Closed 3 years ago.
I have got method:
private bool MyMethod(PlantType plantType)
{
return plantType.PlantMoveType == PlantMoveType.PlantReady
|| plantType.PlantMoveType == PlantMoveType.PlantRelase
}
Can I write it into other way? Maybe with LINQ?

One way is to put the enum values that you want to check against into an array, and call Contains.
return new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
If you are using C# 7 or later, you can also write the method as expression-bodied:
private bool MyMethod(PlantType plantType) =>
new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);

Well a small simplification would be to pass the type (enum?) of the property PlantMoveType instead of PlantType as the parameter.
Beyond that, you could declare the types to check for as e.g. an array. In case you'd like to reuse that array, you can also declare it outside the scope of the method:
private static PlantMoveType[] _plantStates =
new []{PlantMoveType.PlantReady, PlantMoveType.PlantRelase};
private bool MyMethod(PlantMoveType plantMoveType)
{
return _plantStates.Contains(plantMoveType);
}

Related

Is it possible to add methods into variables [duplicate]

This question already has answers here:
Easiest way to extend a Struct (PointF)
(3 answers)
Extension methods versus inheritance
(9 answers)
Extend an existing struct in C# to add operators
(7 answers)
A way to extend existing class without creating new class in c#
(3 answers)
Closed 1 year ago.
Is it possible to add methods into variables, example being.
public static int BoolToInt(bool entry)
{
if(entry == true) { return 1; }
else { return 0; }
}
bool example = checkbox1.Checked;
RandomMethod(example.BoolToInt());
Looking into minimizing visual clutter and help readability (I find RandomMethod(example.BoolToInt(), example2.BoolToInt()); easier to read than RandomMethod(BoolToInt(example), BoolToInt(example2));) I was wondering if this was possible, upon research I found this Can you assign a function to a variable in C#? which feels like it's the right direction, but it makes the variable become the method, when I want to just add into it. I'm a newbie so I couldn't go from there to what I want nor know if it's theres a way to do it, also couldn't find much reading the Microsoft Docs.
You can use C# extension methods to "extend" exists types by declaring new methods for the extended type.
static class BoolExtensions {
public static int ToInt(this bool value) {
return value ? 1 : 0;
}
}
Then you can use as:
var example = true;
var exampleAsInt = example.ToInt();
Reference:
Extension methods

Contains function for C# (Linked list) comparing issue [duplicate]

This question already has answers here:
C# difference between == and Equals()
(20 answers)
Are string.Equals() and == operator really same? [duplicate]
(8 answers)
Closed 5 years ago.
I'm writing a simple contains function which accepts a value and checks if it exists in the linked list. Returns a bool. However, when temp.Data is the same as data, as checked through debugging, it still proceeds to enter the while statement and cycle through the list, as if they are not equal. I have found a solution, by using toString() on all values. So I have to compare temp.Data.ToString() and data.ToString(). Then it works...I am new to C#, I haven't used the Object keyword much. I'm wondering if it's something to do with that? So my function works with my quick fix but I'm trying to understand why...thanks!
public bool Contains(Object data)
{
Node temp = head;
while((temp.Data != data) && (temp.Next != null))
{
temp = temp.Next;
}
//Rest of code

C# - Compare one string variables to multiple other string (String.Equals) [duplicate]

This question already has answers here:
Multiple string comparison with C#
(8 answers)
Closed 5 years ago.
Do you have an idea to avoid doing multiple String.Equals?
For instance:
if (interSubDir.Equals("de") || interSubDir.Equals("de-DE"))
Thanks!
If you are simply trying to make it more readable, or require less typing, you can write a string extension method like so:
public static class StringExt
{
public static bool EqualsAnyOf(this string value, params string[] targets)
{
return targets.Any(target => target.Equals(value));
}
}
Which you can use as follows:
if (interSubDir.EqualsAnyOf("de", "de-DE"))
Or
if (interSubDir.EqualsAnyOf("de", "de-DE", "en", "en-GB", "en-US"))
and so on.
Create collection of values:
string[] values = { "de", "de-DE" };
Use Contains method:
if (values.Contains(interSubDir))
It gives O(n) performance.
If your collection is very big, then you can use Array.BinarySearch method, that gives you O(log n) performance.
if (Array.BinarySearch(values, interSubDir) >= 0)
However, the collection must be sorted first.
Array.Sort(values);
Linq could come into help for you. listToChechAgainst could be simple variable or private/public property.
var listToChechAgainst = new[] { "de", "DE-de" };
if(listToChechAgainst.Any(x => innerSubDir.Equals(x)));

Associate variable to a list [duplicate]

This question already has answers here:
Interesting "params of ref" feature, any workarounds?
(5 answers)
Closed 7 years ago.
I'm not sure if this is easy possible in C#. But I would like to get to know how this could be done easily.
public partial class Form1
{
// I left out the unimportant code for this example
private myControl cLeft,cTop,cBottom,cRight;
private List<myControl>mControls;
public Form1()
{
InitializeComponents();
//this list should contain the fields cLeft,cTop,cBottom,cRight...
mControls=new List<myControl>(){cLeft,cTop,cBottom,cRight};
/* now I want that cLeft and so on get assigned...
of course, this doesn't work because the list refers to the values of
cLeft ... which are null. So I would need to store a reference to those fields to get this work.*/
mControls.ForEach(x=>x=new myControl(this));
}
}
I'm sure it could be done through reflection, but I assume that there should be a way to do this easily in C# or isn't it possible?
It's just a simple loop, there is no need to use LINQ. You just need a for loop.
for (int i = 0 ; i < mControls.Count ; i++) {
mControl[i] = new myControl(this);
}
But, there is no need to write cLeft, cTop etc. You can just refer to them using the indexer: mControls[0], mControl[1] etc.
And remember, the foreach loop or the ForEach extension method doesn't work. This is because you are changing the reference of the variable. That is just another confusing (for beginners) feature of reference types!
Consider this method
public void ChangeReference (string s) {
s = "Hello";
}
And you call this method:
String s = "xxx";
ChangeReference (s);
Will s be "Hello" after the call? No. In the method, you are changing the location of the string in memory, but the argument is still in the same place!

Can IEnumerable be an alternative to Params[]? [duplicate]

This question already has answers here:
Why use the params keyword?
(11 answers)
Closed 7 years ago.
Can IEnumerable be a possible alternative to params[]?
Because Ive been hearing some articles that params is not good, but I seem to doubt it because it is syntactically straightforward and is very useful.
ex.
public void testMeth(IEnumerable<object> testerEnum){
//Code here
}
Using the params keyword importantly allows callers of your method not to wrap the arguments into a collection at all.
With:
public bool testMeth(params object[] input){
// ... things
return purity >= REQUIRED_PURITY; //this is how to test meth, right?
}
The caller can call
var is_good = testMeth("apples", new object(), 7);
with no need to make their own array.

Categories