Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have an "alias" for byte array in C#?

Tags:

c#

I want to call an overloaded callback method that can accept several different types as possible arguments.

string s = "some text";
PerformCallback(s);

int i = 42;
PerformCallback(i);

byte[] ba = new byte[] { 4, 2 };
PerformCallback(ba);

So far no problem. But now I want to have two different kinds of byte arrays, let's call them blue byte arrays and green byte arrays. The byte arrays themselves are, well, just byte arrays. Their blueness and greeness is only a philosophical concept, but I'd like to write an overloaded callback method that has two different overloads for the two kinds of byte arrays, and a way of invoking the two different overloads. I'd prefer very much to avoid having to use an extra argument to indicate the color of the byte arrays, and I'd prefer to avoid anything that adds an enclosing class or similar that will add runtime overhead.

Any ideas? Thanks in advance.

like image 278
RenniePet Avatar asked Sep 01 '25 03:09

RenniePet


1 Answers

Well, you could create a struct which just contains a byte array, and then possibly have implicit conversions to/from byte[]... that way you end up with separate types for the sake of overloads etc.

As it's a struct there would be no overhead in terms of memory - there may well be a very slight overhead involved in running the operator (or just the constructor) but it's at least likely that the JIT will inline everything to heck anyway. I certainly wouldn't expect it to have a significant performance impact.

(To be honest, you could make it an enclosing class and you'd still be unlikely to notice any difference unless this was being used in a tight loop, IMO. Performance bottlenecks are rarely where we expect them to be.)

like image 140
Jon Skeet Avatar answered Sep 02 '25 15:09

Jon Skeet