Help understand type casting

K

keithb

I'm trying to understand C# type casting. The following code will not
compile unless I Cast item to a String.

private static String myData;

foreach (DataRow row in MyTable.Rows)

{
foreach (Object item in row.ItemArray)
{
myData = item;
}
}

However when I use plus-equal instead of equal it compiles without casting
as shown in the code below.

foreach (DataRow row in MyTable.Rows)

{
foreach (Object item in row.ItemArray)
{
myData += item;
}
}

Can someone explain the difference?
 
A

AlanT

The issue isn't the casting per se as the + operator. It is performing
the conversion from object to string for you

e.g.

string str = "foo";
object obj = "bar";

string msg = obj; ' gives, cannot do an implicit
cast from object to string

string otherMsg = str + obj; ' works fine.


because the + operator adds the ToString() output from the object


e.g.

string str = "foo";
object obj = 17;

string otherMsg = str + obj; ' gives foo17

object obj = new Widget();

otherMsg = str + obj; ' gives fooMyNamespace.Widget


hth,
Alan.
 
R

Rene

In C# there are Primitive, Reference and Value type variables. In
particular, the primitive variables are variable that the compiler supports
directly such as String. Int, Double etc variables. This means that the
compiler has its own little rules on how to manage these primitive
variables.

In your example, the compiler automatically converted the object to a string
(ToString()). The compiler is set up to do that when you add a string with
something else that is not a string.

If you look at the definition of a string, you will notice that there are no
operator overload definition for operator such as +,-,*, division etc. as I
said before, the reason for this is because the compiler has its own set of
rules for this types of operation.

If you where to perform your example with one of your custom classes (where
you don't supply an operator overload for + that know how to handle adding a
string) the instruction were you add the variables will give you a compile
error. The reason for this is because internally, the compiler knows nothing
about how to perform operations with your own custom classes, you have to
tell the compiler what to do.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top