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
  • 101,809
  • 122
  • 424
  • 632
  • 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
  • 202,030
  • 26
  • 332
  • 449