Implicit Conversion in abstract class

Viewed 207

I have an abstract object Arg is there any chance to use it like this:

Arg<string> Title = "Big Title";

Console.WriteLine(Title);

Output should be: "Big Title"

Can i use implicit operator ?

Base Class is :

public abstract class Arg<T>
        where T: class,new()
{
        
        public object Value { get; set; }
    
        public Arg() 
        {
            Value = new T();

        }
 public static implicit operator T(T t) 
        {
            return t or Value  ;
        }
        public override string ToString() 
        {
            return Value.ToString();
        }   
}    

Any ideas are welcome. Thanks in advance

1 Answers

You won't be able to construct abstract class. However, you can make it non-abstract and create implicit convertion to it. For example:

public class Arg<T>
{
    public Arg()
    {
        Value = default(T);
    }

    public T Value { get; set; }

    public static implicit operator Arg<T>(T value)
    {
        return new Arg<T> { Value = value };
    }

    public override string ToString()
    {
        return Value?.ToString();
    }
}

And then you'll be able to write:

Arg<string> s = "Hello, world";
Console.WriteLine(s);
Related