string someVariable = (string) someOtherVariable;
This is your good old ordinary casting, and it will throw an exception if you try to inject something into something that CANNOT be thrown (thus, you need to check several times if they are any)
string someVariable = someOtherVariable.ToString();
not really casting, it executes a method that can come from different places (interfaces), but that ALL objects in C # have, since they inherit the Object object that has it. It has a default operation that gives the type name of the object, but you can overload it to print everything you want your class to print using the ToString method.
string someVariable = someOtherVariable as string;
This is new C # casting, it first checks to see if it can be hidden using variable is string , and then casts if it is valid or returns null if it is not, so it could be a silent error if you expect exceptions, since you should check for null.
Mostly
myType as myOtherType
matches with:
var something = null; if(myType is myOtherType) { something = (myType) myotherType; }
except that it will be checked and discarded in one step, and not in 2.
Francisco noriega
source share