views:

66

answers:

2

Hi!

Is there a way to declare that the variable type of a generic class must be serializable?

Best Regards
Oliver Hanappi

+1  A: 

You can check the interface but not the attribute:

public void DoSomething<T>( T input ) where T:ISerializable { ...

Attributes can only be checked at run-time though, so you can't enforce their usage with a constraint

Keith
Classes marked with the attribute will not implement (with much magic) this interface, do they?
Oliver Hanappi
No - you can mark a class with [Serializable] or you can make them implement the ISerializable interface. You can only constrain for the interface.
Keith
ISerializable lets you override the default serialisation process, while the [Serializable] attribute just lets the CLR know that this class can be serialised.
Keith
You can only throw a run-time exception in constructor.
Groo
+1  A: 

One option would be to set a validation in the beginning of your method and use reflection to check if the serialization attribute exists but this is only an execution time check. You louse all the purpose of generics witch provide compile time type safety. If you have absolute control over the Types that are being passed to your method, you could set a unit test to check if the attributes exist. This would be a part of your build process.

bruno conde