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?
In the C programming language, restrict is a keyword, introduced by the C99 standard, that can be used in pointer declarations. By adding this type qualifier, a programmer hints to the compiler that for the lifetime of the pointer, no other pointer will be used to access the object to which it points.
Restricted pointers in C99 The C99 keyword restrict is an indication to the compiler that different object pointer types and function parameter arrays do not point to overlapping regions of memory. This enables the compiler to perform optimizations that might otherwise be prevented because of possible aliasing.
Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier.
For example, char const * restrict is a type. Actually, it only applies to pointer types, i.e. T * restrict . So int restrict is invalid, but int * restrict is valid. In a function, a parameter T * restrict p means that the allocated object pointed at by p is only pointed at by p .
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
public static bool IsTypeSerializable(this Type type) {
Contract.Requires(type != null);
return type.GetCustomAttributes(typeof(SerializableAttribute), true)
.Any();
}
and say
Contract.Requires(typeof(T).IsTypeSerializable());
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
where T : ISerializable
Again, not the same thing, but it's something to consider.
Unfortunately, no, you cannot create a generic constraint that checks attributes. The best you can do would be to implement the constraint at runtime:
if (!typeof(T).GetCustomAttributes(typeof(SerializableAttribute), true).Any())
{
throw new ArgumentException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With