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?
Asked
Active
Viewed 59 times
0
-
1Can you provide code that you have tried? – Manprit Singh Sahota Apr 13 '17 at 05:39
-
Oh, if nothing changed in C#, the answer is "no": http://stackoverflow.com/questions/5526601/can-i-add-an-implicit-conversion-for-two-classes-which-i-dont-directly-control – Bloodskys Apr 13 '17 at 05:42
-
@ManpritSinghSahota, I really don't think it matters. The key message is obvious: "is it possible, to create type conversion outside the class?" – Bloodskys Apr 13 '17 at 05:49
-
If you really don't want to string everywhere, why not make it accept an object or make an overload that accepts an object and tostring in this method. I know it's terrible practice but it would work in your case. – Joel Harkes Apr 13 '17 at 05:56
-
@JoelHarkes, you are right. Just would know if there is a better way :) – Bloodskys Apr 13 '17 at 06:08
-
@Bloodskys hehe There you hit an interesting statement 'better'. Some would say implicit conversion is never better because its a secret type cast ;-) – Joel Harkes Apr 13 '17 at 06:46
1 Answers
0
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.
Addition
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)

Community
- 1
- 1

Joel Harkes
- 10,975
- 3
- 46
- 65