3

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

3
  • 1
    Why is your property of type object and not T?
    – Fildor
    Mar 2, 2021 at 7:36
  • 1
    "I have an abstract object Arg" why is it abstract?
    – Mong Zhu
    Mar 2, 2021 at 7:37
  • 1
    It was intended as a base class
    – adi sba
    Mar 2, 2021 at 7:40

1 Answer 1

5

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);
1
  • @pinkfloydx33 Agree, added '?' check to ToString()
    – Quercus
    Mar 2, 2021 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.