I have the following method declaration:
public static bool SerializeObject<T>(string filename, T objectToSerialize){
I want to restrict T to types decorated with the [Serializable] attribute.
The following does not work because “Attribute ‘System.SerializableAttribute’ is not valid on this declaration type. It is valid on ‘Class, Enum, Struct, Delegate’ declarations only.”:
public static bool SerializeObject<T>(string filename, [Serializable] T objectToSerialize)
I understand that AttributeUsageAttribute(AttributeTargets.Parameter) must be set for the Attribute in order to use the above and that the [Serializable] attribute does not have this set.
Is there a way to restrict T to types marked with the [Serializable] attribute?
No, there is not a way to do this using generic constraints. These contraints are clearly spelled out in the specification and this is not one of them.
However, you could write an extension method
and say
No, it’s not the same thing, but it’s the best that you can do. The constraints on generics are fairly limited.
Lastly, you could consider saying
Again, not the same thing, but it’s something to consider.