views:

349

answers:

2

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.

+14  A: 

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.

Neil Williams
This is exactly what the asker is looking for. It's not exactly a "custom primitive", but it mimics one as well as possible, and is the right way to go in C#.
Noldorin
If you make it a struct, you should **absolutely** make it immutable at the same time; having a {get;set;} on a struct is a very, very bad idea. Did I mention the badness?
Marc Gravell
Totally agreed, sorry for the confusion. I was originally, wrongly, trying to mimic his example as closely as possible.
Neil Williams
Cheers for fixing; I'll give it a +1 with that tweak ;-p
Marc Gravell
Thankyou muchly, good sir!
Neil Williams
Thanks, this has been quite informative!
+1  A: 

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.

Lucas Jones
Not sure it's invariably "bad practice". Depends on the context, in my opinion.
Noldorin
Using conversion operators on reference types hides the instantiation of new objects; or worse, returns an old reference which for mutable types (not the string) can only cause trouble.To me it's preferable with conversion operators on value types only, and leave reference types to up- and downcasts.
Cecil Has a Name