I ran into a bug that was bothering me. I had JObject that I thought would be fine with
obj["role"].ToString()
The string was there and everything. A final resort was to change to a
(string)obj["role"]
just to see what happens and it works. My question is how do I know when to use a .ToString() as opposed to a (string) as opposed to an “as String”.
If the object is a
string, or there is an explicit cast operator to(string), then it is okay to sayOtherwise, this will give you an
InvalidCastException.Note that here you could say
which will set
stonullifobj["role"]is not an instance ofstring. Note that foras, explicit cast operators are ignored.If
obj["role"]is neither astringnor an instance of a class that has an explicit cast operator tostring, you have to sayBut be careful, the latter can throw a
NullReferenceException.