Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use "where" to require an attribute in c#?

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] 
like image 348
juan Avatar asked Oct 21 '08 12:10

juan


People also ask

What is use of attributes in C#?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.

How do you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);


2 Answers

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.

like image 165
Jon Skeet Avatar answered Oct 21 '22 02:10

Jon Skeet


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.

like image 22
Patrik Svensson Avatar answered Oct 21 '22 03:10

Patrik Svensson