Reputation: 21999
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".
Upvotes: 10
Views: 4372
Reputation: 77576
It shouldn't make a difference in your example. The only scenario where it would make a difference is if there is user-type-conversion (to a string
) defined on whatever type obj["role"]
is. In that case it's possibly that the cast to a string
changed it to a different object, upon which the .ToString()
was implemented differently.
Upvotes: 0
Reputation: 1039120
(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.
Upvotes: 2
Reputation: 241701
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
.
Upvotes: 21