1

I have a class which is using generics. This class do some operation which need serialization. So the class which will be given to myClass must hold the attribute [Serializable()]. Is it possible to request a class which attributes it holds? In best case at design time.

    [Serializable()]
    public class clsSchnappschuss<T>
    {
      //Some operations which need serialization
    }

So if someone uses clsSchnappschuss he must give the DataType (T) and i want to request that T implements [Serializable()]. Is this possible?

regards

Sebi
  • 3,879
  • 2
  • 35
  • 62
  • 2
    Have you checked the [documentation](http://msdn.microsoft.com/en-us/library/z919e8tw%28v=vs.80%29.aspx)? – dowhilefor May 27 '13 at 13:00
  • Possible duplicate of http://stackoverflow.com/questions/1226161/test-if-a-class-has-an-attribute – Ben Reich May 27 '13 at 13:01
  • 1
    http://stackoverflow.com/questions/945495/how-can-i-add-a-type-constraint-to-include-anything-serializable-in-a-generic-me – bizon May 27 '13 at 13:03

2 Answers2

4

You cannot request a presence of an attribute statically (i.e. at compile time), but inside the code your generic type you can examine T as if it were an actual type name. For example, you can request its typeof, and pull attributes from it:

public class clsSchnappschuss<T> {
    static clsSchnappschuss() {
        if (Attribute.GetCustomAttribute(typeof(T), typeof(SerializableAttribute)) == null) {
            throw new InvalidOperationException(typeof(T).FullName +" is not serializable.");
        }
    }
}

Note that I put the check in a static constructor. This would execute once before any other code that uses clsSchnappschuss<> for each particular type.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

if your given classes implement the ISerializeable interface you could to following:

public class clsSchnappschuss<T> where T : ISerializable
matthias
  • 101
  • 8