What is the best syntax practice when casting a variable?

Which (if any) is more correct? Why?

string someVariable = (string) someOtherVariable; string someVariable = someOtherVariable.ToString(); string someVariable = someOtherVariable as string; 

I used all three, but I have no preferences or understanding why one is better than the other.

+7
c #
source share
10 answers

These are not all casting examples.

This is the cast:

 string someVariable = (string) someOtherVariable; 

This is the method call:

 string someVariable = someOtherVariable.ToString(); 

And this is a safe listing:

 string someVariable = someOtherVariable as string; 

The first and third examples are actual throws. The first throw has the ability to throw an InvalidCastException , while the third example will not throw this exception. This is why the as operator is known as safe casting.

+10
source share

Here is my article on this topic.

http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx

As for which one is the “most correct”, the most correct is the one that makes sense, which you intend to convey to the reader of the program.

"ToString ()" passes "this is probably not a string, but if not, then I want to get a string from the object that represents it."

The cast statement passes either "this is a string, and I am ready to crash my program, if I am mistaken," or vice versa, this is not a string, and I want to cause the user to convert this object to a string ".

The as operator passes "it may be a string, but if not, I want the result to be zero."

Which of these four things do you mean?

+6
source share

Three do different things - none of them are “more correct”, it depends on your situation. If you have a bunch of objects that might not be strings, you are likely to use .ToString () (with a null check if you expect zeros).

If you care only about non-empty strings, but still expect to get non-non-strings, use "how" and then ignore the values ​​that go into the null value (they were either initially null or non-string type)

if you expect to get only strings, it is best to use (string) cast. This expresses the intention best in code.

 object foo = 5; string str = (string)foo; // exception string str = foo as string; // null string str = foo.ToString(); // "5" object foo = "bar"; string str = (string)foo; // "bar" string str = foo as string; // "bar" string str = foo.ToString(); // "bar" object foo = null; string str = (string)foo; // null string str = foo as string; // null string str = foo.ToString(); // exception 
+5
source share

The as keyword is also useful if you think the conversion will fail during the upgrade. For example, if I want to perform the same operation with similar types in the control list ... say, unchecking all the checkboxes:

 foreach (Control ctrl in Controls) { Checkbox box = ctrl as Checkbox; if (box != null) box.Checked = false; } 

Thus, if there is anything else in my list, such as a text field or label, an exception is not thrown (as it simply sets the variable = null if it does not work), and it is very efficient. No overhead.

+2
source share

The ideas of CAST and CONVERT should not be confused. Casting involves viewing an object as if it were a different type. Conversion involves converting an object to another type.

If you intend CAST on a string, you should use the first or third. (The option depends on what you want to do in an error state. See bangoker .)

If you intend to convert a string to a CONVERT string, you should use the second. (Or better, a modified ChaosPandion statement using the trinary operator.) This is because the behavior of the ToString method is defined as converting the object to a string representation.

+2
source share

This is a 100% personal preference here, but for me I use the following:

 string someVariable = (string) someOtherVariable; 

When converting to a child or parent type (e.g. NetworkStream-> Stream)

 string someVariable = someOtherVariable.ToString(); 

When converting to a new type (int → string)

And I never use the latter (as a string) method, mainly because, based on the background of C / C ++, I prefer (), and this is a bit more concise.

0
source share

There is a big difference between rounding and how.

Basically, an exception will be thrown in parentheses, while "as" will return null instead of raising an exception.

More here

0
source share
 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.

0
source share

First of all, you should avoid castings with the AS operator . This article explains why.

Secondly, you can use the AS operator ONLY if you expect the value to not be of the type you are using. Therefore, you will have to check it manually.

Also, calling the obj.ToString() method is not casting, it converts the object to a string representation (which, in the case of the string itself, is the same string). This can be excluded by any class.


So, as a rule, I follow this:

  • Always use casting (Type) .
  • Use the as operator only if the object can be of a different type than the one you used.
  • If the as operator is used - ALWAYS check the result for NULL.
  • Use ToString only when you need to display object information.
0
source share

If you have a question about best syntax practice when casting a variable, I prefer to use the following:

 var someVariable = someOtherVariable as string ?? string.Empty; 

You can use someVariableDefaultValue instead of string.Empty.

If you are using a complex type rather than a string type, I recommend the following syntax, sometimes called a safe navigation operator:

 var complexVariable = otherComplexVariable as ComplexType; if (complexVariable?.IsCondition) { //your code if cast passed and IsCondition is true } else { //your code if cast not passed or IsCondition is false } 
0
source share

All Articles