C # wrapper primitive

I knew that getting a class from a primitive is not possible, but I would like my class to "look" like a primitive without casting. In this case, my class will work as Decimal:

    public interface IFoo
    {
        static explicit operator Decimal(IFoo tFoo);
    }

    public class Foo: IFoo
    {
        private Decimal m_iFooVal;

        public Decimal Value
        {
            get { return m_iFooVal; }
            set { m_iFooVal= value; }
        }

        static explicit operator Decimal(IFoo tFoo)
        {
            return (tFoo as Foo).Value;
        }

    }

The above code does not work because an explicit statement cannot be defined in the interface. My code deals with interfaces, and I would like to save it that way. Is it possible to convert IFoo to decimal? Any alternatives are welcome. Example:

IFoo tMyFooInterfaceReference = GetFooSomehow();    
Decimal iVal = tMyFooInterfaceReference;
+3
source share
1 answer

Why not just add another method to your IFoointerface called ToDecimal()and call it if necessary?

public interface IFoo
{
    decimal ToDecimal();
}

public class Foo : IFoo
{
    public decimal Value { get; set; }

    public decimal ToDecimal() { return Value; }
}

Your code would not be much more complicated:

IFoo tMyFooInterfaceReference = GetFooSomehow();
decimal iVal = tMyFooInterfaceReference.ToDecimal();
+7
source

Source: https://habr.com/ru/post/1767051/


All Articles