How can I create a value type that can be implemented similar to a Native type

Viewed 60

I would like to create a Type 'Q'.

What I would like to be able to do with the type Q is assign a value similar to the way we assign to native types.

So if the definition were:

public struct Q
{

}

I would like the implementation to be:

Q val = 1.0f

When we look at the struct for a System.Single, we can see that it does not declare any values. But I cannot make sense of what they are doing to enable them to assign a value to the struct itself. How can I make it so that I can assign a value directly to the struct as they do?

1 Answers

"When we look at the struct for a System.Single, we can see that it does not declare any values." That's not correct. Here's the declaration:

 public readonly struct Single : IComparable, IConvertible, ISpanFormattable, IComparable<float>, IEquatable<float>
    {
        private readonly float m_value; // Do not rename (binary serialization)
        // ...
    }

The field m_value is the member field that takes the value when an instance of Single is created. Since it's the only field it's identical to the whole object instance for a value type.

What is different for the built-in-types is that they allow automatic implicit assignment from a value. If you want that for your own types, you need to explicitly declare such an assignment operator. These can be implicit or explicit. You can find examples on how to do that here. Here's a modified example for your case:

public readonly struct MyQ
{
    private readonly int _value;

    public MyQ(int v)
    {
        _value = v;
    }

    public static implicit operator MyQ(int b) => new MyQ(b);

    public override string ToString() => $"{_value}";
}

This can be used as:

   MyQ a = default;
   a = 2;
Related