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();
Actually the best way of writing the code above is to do the following:
That way you're almost certain that it won't cast a NullReferenceException.
The
as
keyword will basically check whether the objectis
an instance of the type, using MSIL opcodeisinst
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'sToString()
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 classobject
's one, returning type info.The first one returns the class as a string if the class is a string or derived from a string (returns null if unsuccessful).
The second invokes the ToString() method on the class.
To confuse the matter further, C# 6.0 has introduced the null-conditional operator. So now this can also be written as:
Which will return either null or the result from ToString() without throwing an exception.
The
as string
check is the object is a string. If it isn't a null it returned.The call to
ToString()
will indeed call theToString()
method on the object.First of all "any-object as string" and "any-object.ToString()" are completely different things in terms of their respective context.
1) This will cast any-object as string type and if any-object is not castable to string then this statement will return null without throwing any exception.
2) This is a compiler-service.
3) This works pretty much well for any other type other than string, ex: you can do it as any-object as Employee, where Employee is a class defined in your library.
1) This will call ToString() of any-object from type-defination. Since System.Object defines ToString() method any class in .Net framework has ToString() method available for over-riding. The programmer will over-ride the ToString() in any-object class or struct defination and will write the code that return suitable string representation of any-object according to responsibility and role played by any-object.
2) Like you can define a class Employee and over-ride ToString() method which may return Employee object's string representation as "FIRSTNAME - LASTNAME, EMP-CDOE" .
Note that the programmer has control over ToString() in this case and it has got nothing to do with casting or type-conversion.