Safe cast

drug drug2004 at bk.ru
Fri Mar 6 13:03:22 UTC 2020


It's too complex

On 3/6/20 3:45 PM, Виталий Фадеев wrote:
> On Friday, 6 March 2020 at 12:35:29 UTC, Виталий Фадеев wrote:
>> Searching info for object casting with checking class type at runtime.
>>
>> Like this:
>>
>> class A
>> {
>>     //
>> }
>>
>> class B
>> {
>>     int bVar;
>> }
>>
>>
>> unittest
>> {
>>     A a = new A();
>>
>>     A x = cast( A )a;     // ok
>>     A x = cast( B )a;     // ok, but unsafe
Here x will be null. You can use `enforce(x !is null);` if you want 
exception.

>>     A x = safeCast( B )a; // throw exception
>>     A x = safeCast( A )a; // ok
>> }
>>


More information about the Digitalmars-d-learn mailing list