C# boxing/wrapper - custom class act as integer

1.8k views Asked by At

At the moment i have this class

public class Currency
{
    private int _Amount;
    public Currency(){... }
    public Currency(int amount){_Amount = amount;}

    public override string ToString()
    {           
        return _Amount + " Gold.";
    }
}

I want this class to have all the functionality of an integer so i can do things like this

Currency curr = new Currency();
Currency curr2 = new Currency(100);
curr = 50; 
curr += 50;
curr += curr2;

i found kinda of what i needed here : Integer c++ wrapper but this is for C++. Can someone tell me how i do this in C#?

public operator Currency() { return _Amount; }

Doesn't work, nor adding implicit/explicit anywhere.

2

There are 2 answers

0
Erti-Chris Eelmaa On BEST ANSWER
class Currency
{
    ...


    // User-defined conversion from Digit to double 
    public static implicit operator int(Currency d)
    {
        return d._Amount;
    }
}

See implicit (C# Reference) for more info. The second thing you want to check, is operator overloading.

0
Aurimas Neverauskas On

What you want is to declare it as struct (so it doesn't get boxed/unboxed, nor cant be null unless you mark it Nullable) and have implicit/explicit converters (can be converted without casts)

    public struct Currency

    public static implicit operator Currency(decimal value)
    {
        return new Currency(value);
    }

    public static implicit operator decimal(Currency me)
    {
        return me.value;
    }