Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic of type T where T has a specific attribute

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
{
    //...
}
like image 303
lkurylo Avatar asked Jul 04 '12 07:07

lkurylo


People also ask

What is generic attribute?

Generic attributes are qualities, skills, and abilities that are valued in study, social situations and employment. They include problem solving ability, teamwork, critical thinking, self-management and basic numeracy.

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

What are generic type constraints?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.


1 Answers

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 {}
like image 190
Frederik Gheysels Avatar answered Sep 21 '22 15:09

Frederik Gheysels