Enum conversion

Russel Winder russel at winder.org.uk
Tue Apr 21 19:20:04 UTC 2020


On Tue, 2020-04-21 at 18:09 +0000, tsbockman via Digitalmars-d-learn
wrote:
> On Tuesday, 21 April 2020 at 16:03:20 UTC, Russel Winder wrote:
> > then which of these is the right way of accessing the value?
> > 
> > cast(ubyte)ZoneNumber.One
> > to!ubyte(ZoneNumber.One)
> 
> Either is acceptable because there is no way that this operation 
> can fail. Using a naked `cast` makes less work for the compiler 
> and performs optimally with or without inlining, though.

Seems like in this case cast is better than to! use.

> > conversely what is the right way of going the other way:
> > 
> > cast(ZoneNumber)1
> > to!ZoneNumber(1)
> 
> Use `to` except where you can gaurantee that the input value maps 
> to a valid enum member, because `cast` does not check your work:
> 
>      writeln(cast(ZoneNumber)17); // breaks the type system
>      writeln(to!ZoneNumber(17)); // throws a ConvException: Value 
> (17) does not match any member value of enum 'ZoneNumber'
> 
> So, `cast` is faster, but unsafe. `to` is slower, but protects 
> the enum's invariant.

Thanks. It seems to! is de rigueur in this case.

-- 
Russel.
===========================================
Dr Russel Winder      t: +44 20 7585 2200
41 Buckmaster Road    m: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20200421/19289e8b/attachment-0001.sig>


More information about the Digitalmars-d-learn mailing list