[Python-ideas] [Wild Idea] Static Ducks

Masklinn masklinn at masklinn.net
Tue Sep 22 23:08:06 CEST 2009


On 22 Sep 2009, at 22:37 , Michael Foord wrote:
>
> C# will not allow you to add strings to numbers, this is nonsense.
I fear you're wrong. In C#, the operation `"foo " + 3` is perfectly
legal and returns `"foo 3"` (and the integer can, of course, be the
left hand of the operator). No need for a ToString, that's implicit.

In fact, this is quite clearly specified in the C# language
specification §7.4.4. "The addition operator"
(http://msdn.microsoft.com/en-us/library/aa691375.aspx):

 > The binary + operator performs string concatenation when one or both
 > operands are of type string. 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
 > virtual ToString method inherited from type object. If ToString
 > returns null, an empty string is substituted.
 >
 >     using System;
 >     class Test
 >     {
 >        static void Main() {
 >           string s = null;
 >           Console.WriteLine("s = >" + s + "<"); // displays s = ><
 >           int i = 1;
 >           Console.WriteLine("i = " + i);        // displays i = 1
 >           float f = 1.2300E+15F;
 >           Console.WriteLine("f = " + f);        // displays f =  
1.23+E15
 >           decimal d = 2.900m;
 >           Console.WriteLine("d = " + d);        // displays d = 2.900
 >        }
 >     }
> If you
> call ToString() then this is an explicit operation to produce a string
> representation - and it is this string that you add. It is *not* at  
> all the
> same as adding arbitrary objects on strings. You can't compile a C#  
> program
> that attempts to add strings and numbers.
You might have wanted to test out this theory.

> I'm also pretty sure you can't override the default behavior on  
> integers etc
> (C# does have operator overloading but doesn't allow you to redefine
> operators on the fundamental types - Java doesn't even have operator
> overloading).
Java somewhat does, since "+" is overloaded on String. What Java doesn't
provide is user-defined operator overloading.




More information about the Python-ideas mailing list