views:

217

answers:

1

I have an interface ISerializeDeserialize defined and some classes inheriting the generic interface. I also have some code generated assemblies using the CodeDomProvider which generates classes inherited from the same interface but implementing it with a specific Type.

What I want to achieve is getting a list of the generic implementations and those implementing the specific type. You can let T=int in the code below.

To get all classes implementing ISerializeDeserialize of some type I so far have this code:

private List<Type> GetListOfGenericSerializers()
{
 Type interfaceGenricType = typeof(ISerializeDeserialize<T>);

 var serializers = from assembly in AppDomain.CurrentDomain.GetAssemblies()
       from genericType in assembly.GetTypes()
       from interfaceType in genericType.GetInterfaces()
        .Where(iType => (iType.Name == interfaceGenricType.Name && genericType.IsGenericTypeDefinition))
       select genericType;

 return serializers.ToList();
}

private List<Type> GetListOfTypeImplementedSerializers()
{
 Type interfaceGenricType = typeof(ISerializeDeserialize<T>);

 var serializers = from assembly in AppDomain.CurrentDomain.GetAssemblies()
       from implementedType in assembly.GetTypes()
       from interfaceType in implementedType.GetInterfaces()
        .Where(iType => iType == interfaceGenricType)
       select implementedType;

 return serializers.ToList();
}

I could pull them together in one function, but I use two for clarity. Question is, can this be optimized or is it done in a better way?

+2  A: 

Unfortunatly I'm not aware of any other way (I also had to write such code more than once).

The one thing you can do is to make the Where in the first method a bit nicer:

private List<Type> GetListOfGenericSerializers()
{
  Type interfaceGenricType = typeof(ISerializeDeserialize<>);

  var serializers =
    from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from genericType in assembly.GetTypes()
    from interfaceType in genericType.GetInterfaces()
    where genericType.IsGenericTypeDefinition &&
          interfaceType.IsGeneric &&
          interfaceType.GetGenericTypeDefinition() == interfaceGenericType
    select genericType;

  return serializers.ToList();
}
Thomas Danecker
It's checking of the .Name property in the first loop which bothers me the most, since it's not 100%. If someone creates another interface with the same name it could match. Guess I could add some logic to check on the FullName instead.
Mikael Svenson
Added a better version to my answer.
Thomas Danecker
Thanks.. learn something every day :)
Mikael Svenson