Reputation: 1
I have a method, that takes a string as a parameter. When I send a JToken, I get cast error. Of course, I can use JToken.ToString(), but if I have a lot of JTokens, it becomes hard to handle all of them. Is it possible to create implicit type casting from JToken to string (for example), considering I don't have access to the JToken or string class changing?
Upvotes: 0
Views: 63
Reputation: 11661
To sum up what everybody has been saying: No this is not possible.
You can only implicit type cast when you own one of the classes: Can I add an implicit conversion for two classes which I don't directly control?
The best way (in my opinion) To solve this problem is to use an extension method accepting JToken instead of string and tostring() it:
public static class MyExtensionMethodWrap
{
public static void AcceptJtoken(this ClassYouWantToExtend self, JToken token)
{
self.AcceptJtoken(token.ToString());
}
}
This way you don't make an useless and confusing method on the ClassYouWantToExtend
but you do have the possibility for yourself to directly inject the JToken.
You can make the extension method/class internal so this method is only available inside your single project. (not creating confusion anywhere else, by showing this method)
Upvotes: 0