Generic of type T where T has a specific attribute
Asked Answered
B

3

12

Is it possible to create a generic method of type T where T has a specific attribute?

E.g.:

public static XmlDocument SerializeObjectToXml<T>(T obj)
{
    //...
}

and I want to serialize only a classes with a Serializable and/or DataContract attribute:

[Serializable]
[DataContract(Name = "viewModel", Namespace = "ns")]
internal class ViewModel
{
    //...
}
Bes answered 4/7, 2012 at 7:54 Comment(1)
You have to ask, will that be generic?Van
C
11

I'm afraid no. There are 3 types of constraints: derivation, constructor and reference/value-type.

I believe, you should check for attributes in the method body and if the serializable object doesn't meet the criteria call a different method to process it.

Cianca answered 4/7, 2012 at 7:58 Comment(0)
P
7

Perhaps you can do it indirectly, by creating a base-class which has the Serializable attribute, and add a constraint to your generic class, so that the type-parameter should inherit from that base-class:

[Serializable]
public class MyBase {}

public static XmlDocument SerializeToXml<T>( T obj ) where T : MyBase {}
Palmira answered 4/7, 2012 at 8:5 Comment(1)
Keep in mind, though, not all attributes are inheritable. When declaring custom attributes you must make them inheritable for this approach to work: [System.AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]Oops
K
1

Statically, I don't think so. But you could check the type T at runtime:

var isDataContract = typeof(T).GetCustomAttributes(typeof(DataContractAttribute), true).Any();
if (!isDataContract) throw new InvalidOperationException("You can only serialize classes that are marked as data contracts.");
//... continue serialization
Kaden answered 5/7, 2012 at 15:59 Comment(1)
Why is the .Cast<>.Any() required? Since you're specifying DataContractAttribute in the GetCustomAttributes() call, shouldn't a length greater than 0 of the returned object[] be a sufficient test?Calibrate

© 2022 - 2024 — McMap. All rights reserved.