Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible create extended boolean? [closed]

Tags:

c#

So basically I would like to create an extended boolean. The base one has Equals, CompareTo functions, but I would like to create a bool type which has some other functions, methods...

For example:

extbool eb = true;

var pos = eb.position

or

eb.get...()

Is there any possibility to do this in C#?

like image 341
user1692315 Avatar asked May 10 '26 03:05

user1692315


2 Answers

I'm not quite sure the purpose for additional methods on the Boolean type, but you can use extension methods.

Example (change the return type to whatever you need):

public static class BoolExtensions
{
    public static int Position(this bool val)
    {
        return 2;
    }
}

Call it:

bool foo = false;
int position = foo.Position();
like image 160
matth Avatar answered May 12 '26 18:05

matth


You can define your own class and override the implicit cast operator to boolean:

public static implicit operator extbool  (bool instance)
   {
        //implicit cast logic
        return extbool ;
   }

Now you can easily do:

extbool a = true;

and the opposite:

public static implicit operator bool (extbool  instance)
   {
        //implicit cast logic
        return extbool ;
   }

This should let you also do comparisons also cast into/from a boolean. Here's a nice article that explains everything

http://www.codeproject.com/Articles/93160/Operator-Overloading-with-Implicit-and-Explicit-Ca

like image 31
Samy Arous Avatar answered May 12 '26 16:05

Samy Arous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!