Re: Generics and Casting - strange behaviour

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Andrew Ducker wrote:
Jon Skeet [C# MVP] wrote:
The best thing to do, if you have access to Validator, is to have some
sort of generic conversion interface so it doesn't need to rely on
compile cleverness in the first place. I don't believe there's any way
of using user-defined conversions in a generic context.

Well, it can clearly manage, when the constraints are right - otherwise
the first coding example wouldn't work. I'll have to take a further
look into it when I have more time.

Ah - I've just looked at the samples again. The second sample wouldn't
have worked even without generics. User-defined conversions are applied
at compile-time, so if you did:

Object o = myValidator;
ValidTextBox vtb = (ValidTextBox) o;

you'd run into the same exception.

I'm frankly surprised that the user-defined conversion is applied in a
generic way to start with though. I might have to play around with
that. I tend to avoid user-defined conversions, to be honest... I like
casts to really be casts :)

Jon

.