Generics: how to have a constraint on an attribute?

M

Matteo Casati

Guest
Hi,
I would like to set a constraint (where keyword) on a type in a generic
class, based on the [Serializable] attribute to accept as "T" type each class
marked as serializable.
Is it possible? If yes, how to do? Else... why not??? :)
Thanks


 


> Is it possible?
Not at compile time via a constraint, no.

At runtime, you could check via reflection, but you don't get many
benefits doing this.

> why not???

Remember that constraints are compile-time; how many permutations /
combinations should it support? what are the common use-cases? what
level of complexity? Personally I find that the existing limits do
what I need.
A more common question is "can I tell it to demand a constructor
matching (int, string)" etc, but again this isn't supported - just
parameterless.

Marc


 
On Nov 16, 11:48 am, "Marc Gravell" <marc.grav...@gmail.com> wrote:

<snip>

> A more common question is "can I tell it to demand a constructor
> matching (int, string)" etc, but again this isn't supported - just
> parameterless.


The two I'd like supported are "T derives from System.Enum" and "T
derives from System.Delegate" - but both of these are specifically
*excluded* from the normal derivation constraints, which is a bit of a
pain :(

Jon
 
"Marc Gravell" wrote:


> Not at compile time via a constraint, no.


Ok :-(

> At runtime, you could check via reflection, but you don't get many
> benefits doing this.


Yeah, but this is not a solution: I will have compile time errors also
without the check on IsSerializable :)

> Remember that constraints are compile-time; how many permutations /
> combinations should it support? what are the common use-cases? what
> level of complexity? Personally I find that the existing limits do
> what I need.


I agree!

Thank your for your reply.
Have a nice day.
 
> [...] both of these are specifically
> *excluded* from the normal derivation constraints, which is a bit of a
> pain :(


Current supported constraints are too poor to be useful :-(
We can only hope to have an extension of "where" keywords in one of the the
next releases.

Thanks for your answer.
Bye
 
Matteo Casati <MatteoCasati@discussions.microsoft.com> wrote:
> > [...] both of these are specifically
> > *excluded* from the normal derivation constraints, which is a bit of a
> > pain :(

>
> Current supported constraints are too poor to be useful :-(


I wouldn't say that. They're not as useful as they *might* be, but
they're still useful.

> We can only hope to have an extension of "where" keywords in one of the the
> next releases.


Unfortunately I suspect that would require CLR support, which is
obviously more significant than just library or language support :(

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
 

Back
Top