Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# overloading implicit conversion referencing the old value

Even tho I'm pretty sure there might be no solution for my problem, I still wanna give it a try and ask you guys for some advice.

Let's say I have a simple class like

public class MyIntContainer
{
   public int myIntValue;
   public bool randomOtherValue;

   public MyIntContainer(int value)
   {
      myIntValue = value;
   }
}

now I want to assign my variable simply like this:

MyIntContainer container = 10;

So the easiest way would be to add an implicit conversion operator to my class like so

public static implicit operator MyIntContainer(int value)
{
   return new MyIntContainer(value);
}

The problem is: I want to keep the randomOtherValue, if there was any. So if I do something like this:

MyIntContainer container = new MyIntContainer(10);
container.randomOtherValue = true;
container = 20;

I want the latest container-variable to have myIntValue = 20 and randomOtherValue = true; I just can't seem to find any way to do this. If only we could overload the assignment operator in any way, such thing could be possible. I even thought about giving the implicit operator-method an additional "this MyIntContainer container" parameter, which could refer to the variable which is stated before the assignment operator. But obviously none of that works. Are there any nice tricks to emulate such a behaviour?

thanks in advance, greetings BOTHLine

like image 901
BOTHLine Avatar asked Nov 17 '25 13:11

BOTHLine


1 Answers

It doesn't make sense for an assignment operator to combine values with the old value-- that is not what that symbol means.

However you could overload | (logical OR), which could arguably signify the combination of values (for example 0x10 | 0x01 = 0x11).

public class MyIntContainer
{
    public int myIntValue;
    public bool randomOtherValue;

    public MyIntContainer(int value)
    {
        myIntValue = value;
    }

    static public MyIntContainer operator | (MyIntContainer lhs, int rhs)
    {
        return new MyIntContainer(rhs) { randomOtherValue = lhs.randomOtherValue };
    }
}

Test:

var x = new MyIntContainer(10);
x.randomOtherValue = true;
x |= 20;   //Combine x with the new value of 20

Console.WriteLine("{0} {1}", x.myIntValue, x.randomOtherValue);

Output:

20 true
like image 168
John Wu Avatar answered Nov 20 '25 02:11

John Wu



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!