How to work with an Interface that inherits IDictionary and set desrialize object return type as that interface

87 Views Asked by At

Here I have one interface which inherits IDictionary and what I want is to get return type of that interface

  1. Interface class

using System.Collections.Generic;

public interface IClientSettings : IDictionary<string, string>
{

}
  1. Code part of method where jsondata was deserialize to list dictionary

if (result.StatusCode == HttpStatusCode.OK)
{
    DashboardJsonConverter jsonConverter = new DashboardJsonConverter();
    var keyValues = jsonConverter.DeserializeClientSettings(jsonData); //desrialize obj
    result.Dispose();//dispose response
    return (IClientSettings)keyValues;
}
  1. Deserialize method

public List<Dictionary<string, string>> DeserializeClientSettings(string json)
{
    return JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
}
1

There are 1 best solutions below

0
D Stanley On

There is no way in the C# type system to safely downcast one type to another.

List<Dictionary<string, string>> has no knowledge of IClientSettings so you can't cast that type to it. You will need to create a concrete type that does implement that interface, and create a way to create that type from a List<Dictionary<string, string>>. What you could do is create an "adapter" type that wraps a List<Dictionary<string, string>> and passes through any method call to the underlying type.