Difference between .ToString and "as string" in C#
What is the difference between using the two following statements? It appears to me that the first "as string" is a type cast, while the second ToString is an actual call to a method that converts the input to a string? Just looking for some insight if any.
Page.Theme = Session["SessionTheme"] as string;
Page.Theme = Session["SessionTheme"].ToString();
If Session["SessionTheme"]
is not a string
, as string
will return null
.
.ToString()
will try to convert any other type to string by calling the object's ToString()
method. For most built-in types this will return the object converted to a string, but for custom types without a specific .ToString()
method, it will return the name of the type of the object.
object o1 = "somestring";
object o2 = 1;
object o3 = new object();
object o4 = null;
string s = o1 as string; // returns "somestring"
string s = o1.ToString(); // returns "somestring"
string s = o2 as string; // returns null
string s = o2.ToString(); // returns "1"
string s = o3 as string; // returns null
string s = o3.ToString(); // returns "System.Object"
string s = o4 as string; // returns null
string s = o4.ToString(); // throws NullReferenceException
Another important thing to keep in mind is that if the object is null
, calling .ToString()
will throw an exception, but as string
will simply return null
.
The as
keyword will basically check whether the object is
an instance of the type, using MSIL opcode isinst
under the hood. If it is, it returns the reference to the object, else a null reference.
It does not, as many say, attempt to perform a cast as such - which implies some kind of exception handling. Not so.
ToString()
, simply calls the object's ToString()
method, either a custom one implemented by the class (which for most in-built types performs a conversion to string) - or if none provided, the base class object
's one, returning type info.