Similar alternative to extraction/insertion operator overloading in C# that exists in C++
Similar alternative to extraction/insertion operator overloading in C# that exists in C++
I'm currently working on a Packet class for a C# project.
In my C++ version of my Packet class, I have extraction and insertion operators so a packet with multiple integers/strings/etc can be built in as few lines as possible like so.
std::shared_ptr<Packet> p = std::make_shared<Packet>(PacketType::Test); //Create packet of type (Test)
*p << 3 << "John" << "Hates" << "Susan"; //append data to packet
myConn.SendPacket(p); //queue packet to be sent
I am trying to figure out if there is a way I could get similar functionality in C# or if I will really be forced to have a separate line for each piece of data being fed to/extracted from the packet.
In C# I am imagining the equivalent will look something like this...
Packet p = new Packet(PacketType::Test); //Create packet of type (Test)
p.Append(3);
p.Append("John");
p.Append("Hates");
p.Append("Susan");
myConn.SendPacket(p); //queue packet to be sent
Is there any way I can cut down on lines of code while not negatively impacting performance? I am not looking to fill the data into a string. I want it to stay as binary data.
I specifically put that I am not looking to fill the data into a string. I want it to stay as binary data. Thanks for the suggestion however.
– user2980207
Jul 2 at 17:34
1 Answer
1
You can define your Append method like below:
Append
public void Append(params object args)
{
// todo: save your args here
}
params keyword will allow you to add as many arguments as you want (just like in printf function). Usage is:
params
printf
Packet p = new Packet(PacketType::Test); //Create packet of type (Test)
p.Append(3, "John", "Hates", "Susan");
myConn.SendPacket(p); //queue packet to be sent
And, as a added bonus, you can look at the type of each argument (say a string, a character, an integer, whatever) and handle each type individually in your Append function. The recent addition of the "pattern matching" switch statement to C# (docs.microsoft.com/en-us/dotnet/csharp/pattern-matching) makes this easier.
– Flydog57
Jul 2 at 18:52
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Use some random string of characters as a delimiter, and then split the string once it is received.
– Ryan Wilson
Jul 2 at 17:30