0

How to give types the ability to initialize via an assignment, some like the following:

public struct WrappedByte
{
    private byte m_value;
}

//Usage:    
WrappedByte x = 0xFF;
Shimmy Weitzhandler
  • 97,705
  • 120
  • 409
  • 613
  • 1
    possible duplicate: http://stackoverflow.com/questions/4537803/overloading-assignment-operator-in-c-sharp – ppetrov May 13 '13 at 17:09

1 Answers1

6

You need to use a custom implicit operator. Note that this doesn't just apply to structs.

public struct WrappedByte
{
    private byte m_value;

    public static implicit operator WrappedByte(byte b)
    {
        return new WrappedByte() { m_value = b };
    }
}

Also note that this won't apply just to initialization; it will mean that you can supply a byte in any location that a WrappedByte is expected. It also includes assignments other than initializations, parameters to methods, etc.

Servy
  • 197,813
  • 25
  • 319
  • 428