37

I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?

The concept I'm looking for is this:

public class MyClass<T> where T : //[is serializable/has the serializable attribute]
juan
  • 80,295
  • 52
  • 162
  • 195

5 Answers5

44

Nope, I'm afraid not. The only things you can do with constraints are:

  • where T : class - T must be a reference type
  • where T : struct - T must be a non-nullable value type
  • where T : SomeClass - T must be SomeClass or derive from it
  • where T : ISomeInterface - T must be ISomeInterface or implement it
  • where T : new() - T must have a public parameterless constructor

Various combinations are feasible, but not all. Nothing about attributes.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
8

What I know; you can not do this. Have you though about adding an 'Initialize' method or something similar?

public void Initialize<T>(T obj)
{
     object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute));
     if(attributes == null || attributes.Length == 0)
          throw new InvalidOperationException("The provided object is not serializable");
}

I haven't tested this code, but I hope that you get my point.

Patrik Svensson
  • 13,536
  • 8
  • 56
  • 77
  • 3
    If you're going to do a runtime test, the IsDefined method is simpler: http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.isdefined.aspx – Jon Skeet Oct 21 '08 at 13:02
  • Yeah, I had though of a runtime check, but wanted to use the where constraint. Thanks for the answer anyway – juan Oct 21 '08 at 17:56
  • Jon: You are absolutely right about this. I don't know how I've missed the IsDefined method, but thank you for pointing it out! – Patrik Svensson Jan 19 '09 at 19:00
4

Afraid not. Best you can do is a runtime check on Type.IsSerializable.

Mark Brackett
  • 84,552
  • 17
  • 108
  • 152
1

If you are looking for any class that is serializable, I think you are out of luck. If you are looking for objects that you have created, you could create a base class that is serializable and have every class you want to support derive from it.

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
1

I know this is old, but I am using a static constructor to check. It is later but allows you to throw an error at runtime.

user2587355
  • 83
  • 1
  • 5