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
Related
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);
}
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!
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.
This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Is there any way I can add a static extension method to a class.
specifically I want to overload Boolean.Parse to allow an int argument.
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
specifically I want to overload Boolean.Parse to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Is there any way I can add a static extension method to a class.
specifically I want to overload Boolean.Parse to allow an int argument.
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
specifically I want to overload Boolean.Parse to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();