Search code examples
c#primitive

Custom primitives in C#?


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.


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.