0

Is there a better way to instantiate a generic type from an actual type variable (with a parameter in the constructor)? In the following code, I abstracted the call to use a helper method. This works, however, resharper complains that the type is an unused variable.

public class CustomSerializerOperationBehavior : DataContractSerializerOperationBehavior
{
    public CustomSerializerOperationBehavior (OperationDescription operation) : base(operation) { }
    public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
    {
        return Helper(type, base.CreateSerializer(type, name, ns, knownTypes));
    }

    public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
    {
        return Helper(type, base.CreateSerializer(type, name, ns, knownTypes));
    }

    // Note update gets the correct type, but I would like to call a specific construct
    private XmlObjectSerializer Helper(Type type, XmlObjectSerializer serializer)
    {
        var genericListType = typeof(JilSerializer<>);
        var specificListType = genericListType.MakeGenericType(type);
        return Activator.CreateInstance(specificListType, serializer) as XmlObjectSerializer;
    }
}
Paul Tsai
  • 893
  • 6
  • 16
  • 2
    Your example does not work like you think it does. T is always of type `Type` not the type of the value of `type.name` – Scott Chamberlain Jun 01 '17 at 15:34
  • Thanks @ScottChamberlain, I've updated the code and it works as expected. Still wondering if there is a better way. – Paul Tsai Jun 01 '17 at 15:49
  • You just showed the better way in your update. Get rid of T entirely, pass in a Type variable to Helper and use the overload of `Activator.CreateInstance` that takes in a string to create the custom serializer. Also in your update T is now always `Object` if that works just get rid of T on the CustomSerializer and use Object everywhere you had T in the code for that CustomSerializer class – Scott Chamberlain Jun 01 '17 at 15:51
  • Your code isn't generic at all, it will always return a `CustomSerializer` – Lee Jun 01 '17 at 15:53
  • Thanks for the suggestions, I've updated my question with the answers. – Paul Tsai Jun 01 '17 at 16:14
  • @PaulTsai Your question has completely changed; it's now asking how to chose a specific constructor. – Rob Jun 02 '17 at 04:49

0 Answers0