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.
"keithb" <kb******@dslextreme.com> wrote in message
news:ew**************@TK2MSFTNGP10.phx.gbl...
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?