Reputation: 73
User-defined conversion must convert to or from the enclosing type.
The problem arises when trying to convert the Dictionary<string,string>
. Is this even possible?
Below is my code.
using Newtonsoft.Json;
public static implicit operator Dictionary<string, string>(string jsonString)
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString); ;
}
public static implicit operator string(Dictionary<string, string> dict)
{
return JsonConvert.SerializeObject(dict);
}
Does it mean that I should write the two methods in Dictionary
Class?
If so, is it impossible to convert string to Dictionary
?
thanks for your help.
Upvotes: 2
Views: 682
Reputation: 39620
You can't define additional conversion operators for Dictionary<string, string>
or string
if they don't convert from or to the type you are defining the operators in, the same way you can't declare additional methods for those types.
You either need to define those conversions as normal static utility methods, or you could define a class derived from Dictionary<string, string>
and define the operators there:
public class StringDictionary : Dictionary<string, string>
{
public static implicit operator StringDictionary(string jsonString)
{
return JsonConvert.DeserializeObject<StringDictionary>(jsonString);;
}
public static implicit operator string(StringDictionary dict)
{
return JsonConvert.SerializeObject(dict);
}
}
Upvotes: 3