Have been playing around with the 4.0 DLR and was comparing dynamic to object and came across this:
Code:
object x = 10;
Console.WriteLine("x = {0} and is a {1}.\n", x, x.GetType());
x = (int)x + 3;
Console.WriteLine("x = {0} and is a {1}.\n", x, x.GetType());
x = x + "a";
Console.WriteLine("x = {0} and is a {1}.\n", x, x.GetType());
Result:
x = 10 and is a System.Int32.
x = 13 and is a System.Int32.
x = 13a and is a System.String.
To me, it looks like object tries to fit the object to a type at runtime (dynamic). However if I don't cast x to an int on the 3rd line, it gives me a compiler area which seems correct for static typing. But then it allows me to add an "a" to x and now it recognizes it as a string.
What am I missing?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
You are missing the fact that the +
operator, when applied to strings, does an automatic conversion (by calling the .ToString()
method on the operand that is not an instance of the String
type).
From the C# Language Specification:
7.8.4 Addition operator
When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.
String concatenation:
string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);
These overloads of the binary + operator perform string concatenation. If an operand of string concatenation is
null
, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtualToString
method inherited from type object. IfToString
returnsnull
, an empty string is substituted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With