-2

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.

PathWalker
  • 17
  • 4
  • 4
    You are looking for [extension methods](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods). – Sweeper Jun 25 '21 at 13:57
  • 1
    Note that if you do decide to use an extension method on a primitive type (which is a dubious practice), be sure to make the containing class `internal`. Otherwise you may bother a lot of code with an extension method they did not expect to be there. – Jeroen Mostert Jun 25 '21 at 14:00
  • Oh, thats perfect thank you, any performance issues I need to be aware of, or that works basically the same as regularly calling methods? – PathWalker Jun 25 '21 at 14:05
  • An extension method is just a static method and has the exact same performance as an ordinary static method. – Olivier Jacot-Descombes Jun 25 '21 at 14:07
  • If we want to convert, why don't we convert: `Convert.ToInt32(example)`? `Convert` is evident, when purpose of `BoolToInt` is not that clear – Dmitry Bychenko Jun 25 '21 at 14:09
  • How is `BoolToInt`/`ToInt` not clear on it's purpose? I see it the same way I see `ToString()`, but again I'm a newbie so I don't know if theres a convention that this would be conflicting with or something along the same lines. – PathWalker Jun 25 '21 at 14:16
  • Typically, when one wants to extend a type, inheritance is the approach. But `bool` is a value type and can't be inherited. For situations where you want to extend a type in a way that can be done using only public members of the type **extension methods** are the language feature you want. See duplicate. – Peter Duniho Jun 25 '21 at 16:44

1 Answers1

0

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:

TheMisir
  • 4,083
  • 1
  • 27
  • 37