The code below is valid:
public class Converter<T,M> : CustomCreationConverter<M>
where T : new()
where M : class
However, this is what I would like to do:
public class Converter<T,M> : CustomCreationConverter<M>
where T : new()
where M : interface
Is something equivalent to this possible?
A constraint that specified that T could be cast as M would also suffice in my specific circumstance.
To clarify, I am not looking for the ability to make T
implement some specific interface.
Someone may try to mark this question as a duplicate of "Force generic interface implementation in C#". Here are the reasons why I believe it is worth not marking my question a duplicate:
- That question is over 8 years old
- The question was resolved when the person posting an answer discovered that the person posting the question actually wanted to know how to implement a specific interface
- If this is not possible through constraints, there may be a workaround
The reason I'm trying to do this is because I'm trying to create multiple custom JSON converters using Json.NET's JsonConverter Class.
public class Converter<T,M> : CustomCreationConverter<M>
where T : new()
{
public override bool CanRead => base.CanRead;
public override bool CanWrite => base.CanWrite;
public override bool CanConvert(System.Type objectType)
{
return base.CanConvert(objectType);
}
public override M Create(System.Type objectType)
{
return new T(); //Cannot implicity convert type 'T' to 'M'
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
public override string ToString()
{
return base.ToString();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
base.WriteJson(writer, value, serializer);
}
}
I could do the above or public class MyClassConverter : CustomCreationConverter<IMyClass>{}
for every class I need a converter for. Just trying to keep things DRY!