Question

Apart from the questionable usefulness of this, I'd like to ask if it is possible to do something along these lines.

class MyPrimitive {
        String value;
        public String Value {
            get { return value; }
            set { this.value = value; }
        }
}

// Instead of doing this...
MyPrimitive a = new MyPrimitive();
a.Value = "test";
String b = a.Value;

// Isn't there a way to do something like this?
MyPrimitive a = "test";
String b = a;

I like to wrap primitive types into custom classes using a property to make the get and set method perform other things, like validation.
Since I'm doing this quite often I thought that it'd be nice to also have a simpler syntax, like for the standard primitives.
Still, I suspect that this not only isn't feasible but could also be conceptually wrong. Any insights would be most welcome, thanks.

Was it helpful?

Solution

Use a value type (struct) and give it an implicit conversion operator from the type you want on the right hand side of assignment.

struct MyPrimitive
{
    private readonly string value;

    public MyPrimitive(string value)
    {
        this.value = value;
    }

    public string Value { get { return value; } }

    public static implicit operator MyPrimitive(string s)
    {
        return new MyPrimitive(s);
    } 

    public static implicit operator string(MyPrimitive p)
    {
        return p.Value;
    }
}

EDIT: Made the struct immutable because Marc Gravell is absolutely right.

OTHER TIPS

You could use implicit casting. It's not recommended, but:

public static implicit operator string(MyString a) {
    return a.Value;
}
public static implicit operator MyString(string a) {
    return new MyString { value = a; }
}

Again, bad practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top