1

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;
}

2 Answers 2

3

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.

6
  • Is it the best pattern to use if I need interface with static members ? For example, I want to be able to instanciate ascx controls with a generic method, to be able to do 'var control = Page.LoadControl<MyControl>();' in place of 'var control = (MyControl)Page.LoadControl("~/MyControl.ascx");'. So I added a AscxPath attribute containing the path to my controls and an extension method on Page, the only thing I don't like about that is there's no compile time check. Commented Feb 11, 2011 at 14:25
  • @Guillaume86: It's not clear to me what the difference would be other than the lack of a cast, to be honest.
    – Jon Skeet
    Commented Feb 11, 2011 at 14:26
  • sorry I didn't explain very well, the static member i needed is the ascx path (controls are in different folders, the example is a simplification). Commented Feb 11, 2011 at 14:30
  • I just want to get rid of all these paths strings each time I instanciate a control (DRY). Commented Feb 11, 2011 at 14:38
  • 1
    @Guillaume86: Okay, I see what you mean. Can you use convention here, and work out the path name based on the type name? I've used that before and it's worked well.
    – Jon Skeet
    Commented Feb 11, 2011 at 14:39
2

You could write a custom FxCop rule to generate warnings for this scenario.

Jason Block has a sample rule on his site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.