Specifically we’re making our application compatible with the Out Of Process Session State server where all types saved in session must be serializable.
Is there a way to see at compile time that any type put into HttpSessionState is marked with the Serializable attribute. Something along the lines of this ‘non-valid’ code
public static void Put<T>( string key, T value ) where T : IsMarkedWitheSerializableAttribute
{
HttpContext.Current.Session[key] = value;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
No, there’s no kind of generic constraint like that. Attributes are generally meant to indicate something about the implementation of a type. You’ll have to either introduce your own marker interface (urgh) or insert an execution-time check and hope that your testing is sufficient.
Eric Lippert’s post about properties and attributes is good to read here. It’s not quite the same question, as it’s talking more about objects vs types, but it’s still relevant in terms of attributes expressing mechanics.
Method 2
You could write a custom FxCop rule to generate warnings for this scenario.
Jason Block has a sample rule on his site.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0