Search code examples
c#objectreturn

Is it possible to override the return of an Object in C#?


I have a LiteralObject class and by default it inherits from System.Object. This is how the class looks like:

    public LiteralObject(Object value)
    {
        this.value = value;
    }
    private Object value;
    public Object getValue() { return value; }

To get the value of a LiteralObject object:

LiteralObject x = new LiteralObject(23);
Console.WriteLine(x.getvalue());

What I want is this:

LiteralObject x = new LiteralObject(23);
Console.WriteLine(x);

Is there a way to override the returning of a System.Object object? or is there any other way to get what I want? Bytheway, overriding ToString() is not the solution I'm looking for. And the object passed into the constructor is of the same type with its parent/base class


Solution

  • You can sort of do that using implicit cast operators. However it doesn't work on object since you can't perform implicit conversion on object (or any other ancestor class). To get around that we can use generics:

    class LiteralObject<T>
    {
        public LiteralObject(T initialValue)
        {
            this.value = initialValue;
        }
        private T value;
    
        public T getValue()
        { 
            return value; 
        }
    
        static public implicit operator T(LiteralObject<T> source)
        {
            return source.getValue();
        }
    }
    
    public class Program
    {
        public static void PrintInteger(int i)
        {
            Console.WriteLine("{0}", i);
        }
        public static void Main()
        {
            var o = new LiteralObject<int>(23);
            PrintInteger(o);
        }
    }
    

    Output:

    23
    

    Example on DotNetFiddle