Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.ToString(), (string), or as String. When to use what?

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".

like image 335
MrM Avatar asked Feb 10 '11 19:02

MrM


2 Answers

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.

like image 136
jason Avatar answered Oct 07 '22 05:10

jason


(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.

like image 30
Darin Dimitrov Avatar answered Oct 07 '22 06:10

Darin Dimitrov