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

Attachment: signature.asc
Description: This is a digitally signed message part

Reply via email to