Click here to Skip to main content
15,902,636 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
For some reason when I write this I keep getting an error that I don't know how to solve. Any help would be very much appreciated!

C#
public static byte[] operator +(byte[] l, byte[] r)
{
    List<byte> blist = l.ToList();
    blist.AddRange(r);
    return blist.ToArray();
}
Posted
Comments
AmitGajjar 5-Sep-12 1:13am    
what error ?

See this C# Operator Overloading[^] and see if it does not answer your question also.
 
Share this answer
 
Comments
JakeTheCoder 4-Sep-12 22:55pm    
Not really...I don't want to have to make a new class that would have to re-implement the whole byte and array class...
[no name] 5-Sep-12 7:06am    
Then you are stuck doing something else for whatever it is that you really want to do.
You can't really overload an operator for the "array" class, since you can only overload operators inside the class itself and not for inbuilt types as byte[]. See this discussion:
http://stackoverflow.com/questions/1687395/overloading-the-operator-to-add-two-arrays[^]

It is currently even not possible to do this in an extension method as discussed here:
http://stackoverflow.com/questions/5518468/is-it-possible-define-an-extension-operator-method[^]

So, your best possible solution is to write a standard function without operator overloading like:
C#
public static byte[] Add(byte[] l, byte[] r)
{
  List<byte> blist = l.ToList();
  blist.AddRange(r);
  return blist.ToArray();
}
 
Share this answer
 
v2
Hi there,
Quote:
When you want to overload le + operator between type AA and BB, you must do it in the class AA or BB and not in a class named Program (like you did).

Unfortunatly, you cannot write code in the Array class.

What you can do is to

create your own class that implements IList
and put the + operator on that class.
I found this on the net and it's true. I know you want to basically overload the operator for convenience, but you cannot do that, so you have to write a helper method. So if you are using .Net 3.5 or higher, here is my solution to you.
C#
public static byte[] Append(byte[] baseData, byte[] newData)
{
  return baseData.Concat(newData).ToArray();
}

If you are using an older .Net framework,
C#
public static byte[] Append(byte[] baseData, byte[] newData)
{
  byte[] result = new byte[baseData.Length + newData.Length];
  baseData.CopyTo(result, 0);
  newData.CopyTo(result, baseData.Length);

  return result;
}

Hope this helps, regards
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900