Operator overloading

G

Guest

I want to overload the + operator for ArrayList for adding elements

public static int operator +(ArrayList l, Object o)

return (l.Add(o))


First I have discovered that the return value cannot be void and if I change it to something like int, I have to always write like this
int i = list + 3; // I don't need
The compiler doesn’t accept jus
list + 3
is there a workaround? I just want to write
list + 3
as a statement and not an expression
 
G

Guest

I have done it this way
public static List operator +(List l, Object o)

l.Add(o)
return (l)


I have just checked the methods. First the normal way of adding to a list

l.Add(2)
it has this MSIL code

IL_0013: ldloc.
IL_0014: ldc.i4.
IL_0015: box [mscorlib]System.Int3
IL_001a: callvirt instance int32 [mscorlib]System.Collections.ArrayList::Add(object
IL_001f: po

Second with my operator overloa
l = l + 3
which gives this MSIL code

IL_0020: ldloc.
IL_0021: ldc.i4.
IL_0022: box [mscorlib]System.Int3
IL_0027: call class [SCollections]Sam.Collections.List SCollections]Sam.Collections.List::blush:p_Addition(class [SCollections]Sam.Collections.List, object
IL_002c: stloc.

What do you think about the performance? Are they that much different
 
J

Jon Skeet [C# MVP]

What do you think about the performance? Are they that much different?

I wouldn't worry about the performance - I suspect it won't be very
significantly different. I'm more worried about the readability - this
is an unfamiliar use of an ArrayList to most .NET programmers. Is this
code for just yourself, or for lots of people?
 
B

Bruno Jouhier [MVP]

Sam said:
I want to overload the + operator for ArrayList for adding elements:

public static int operator +(ArrayList l, Object o)
{
return (l.Add(o));
}

First I have discovered that the return value cannot be void and if I
change it to something like int, I have to always write like this:
int i = list + 3; // I don't need i
The compiler doesn't accept just
list + 3;
is there a workaround? I just want to write
list + 3 ;
as a statement and not an expression.

My 2 cents: normally, an operator like +:

a) produces a result
b) does not modify its operands.

And you are trying to define a + operator that violates these 2 rules.

This is a bad idea. You should keep the method and only define operators
like + when you have a real algebra (operations that don't have side effects
on their operands). Otherwise, you will confuse the people who read your
code.

Bruno.
 

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