views:

40

answers:

1

I know I can:

public class SampleClass<TSerializable>
    where TSerializable : ISerializable

How can I write a SampleClass that accepts only classes marked with the SerializableAttribute instead?

+2  A: 

You can't do this at the compiler, short of something like an fxcop add in.

The best you can do is check (once) at runtime, perhaps via a static constructor that verifies the T in question and throws an error for your unit tests to catch:

public class SampleClass<TSerializable> {
    static SampleClass() {
        if(!Attribute.IsDefined(typeof(TSerializable),
                typeof(SerializableAttribute))) {
            throw new InvalidOperationException("Not [Serializable]:" +
                typeof(TSerializable).Name);
        }
    }
}

[Serializable] class Foo { }
class Bar { }

static class Program {
    static void Main() {
        new SampleClass<Foo>(); // ok
        new SampleClass<Bar>(); // fail
    }
}
Marc Gravell
you answered my next question http://stackoverflow.com/questions/1827296/how-to-check-if-a-type-is-marked-with-an-attribute
Jader Dias