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 say
string s = (string)obj["role"];
Otherwise, this will give you an InvalidCastException
.
Note that here you could say
string s = obj["role"] as String;
which will set s
to null
if obj["role"]
is not an instance of string
. Note that for as
, explicit cast operators are ignored.
If obj["role"]
is neither a string
nor an instance of a class that has an explicit cast operator to string
, you have to say
string s = obj["role"].ToString();
But be careful, the latter can throw a NullReferenceException
.
(string)
casts the instance to string and it might throw an exception at runtime if the object you are trying to cast is not a string. The as
operator also tries to cast but it doesn't throw an exception if the instance is not a string but returns null. And the ToString
method of course comes from System.Object so it will depend on whether tyhe underlying type has overridden it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With