c# - How to Cast A Variable Using Generic Type Parameter and 'as' Operator -
i have following generic static class being used in fluent api. takes input parameter , returns wrapper class containing parameter cast generic type.:
public static foo<tout> inputas<tout>(object parameter) { var castparameter = parameter tout; if(castparameter == null) { throw new exception("invalid cast"); } return new foo<tout>(castparameter); }
the problem castparameter == null
check returns null
. correct way cast object using tout
generic parameter new type?
well, if parameter tout
returns null
, runtime type of parameter
isn't tout
.
don't forget operator resolution done @ compile-time, if have cast operators defined, not invoked here. if need that, can use dynamic
:
public static foo<tout> inputas<tout>(dynamic parameter) { return new foo<tout>((tout)parameter); }
this allow runtime operator resolution, , call cast operator if 1 available. example, allow pass long
, while expecting int
.
however, want find different way of you're trying do; dynamic
can useful, can make debugging quite bit harder, , lose compile-time warnings , errors can identify problems before happen.
Comments
Post a Comment