Jader Dias
Jader Dias

Reputation: 90583

How to specify a generic type should be marked with an attribute?

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?

Upvotes: 1

Views: 131

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064054

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

Upvotes: 3

Related Questions