I have this piece of code right here:
public void SendID(int id)
{
try
{
binaryWriter.Write((int)Command.ID);
// part differening each time
binaryWriter.Write(id);
// end of part differing each time
}
catch (Exception ex)
{
if (Error != null)
Error(this, new ErrorEventArgs(ex));
}
}
I want to generalize this function since the try/catch & Write(Command) thing is always equal on each of those methods. Now I'm wondering what would be the most efficient way to do this?
Basically I thought of a method saying something like this:
public void SendCommand(Command cmd, Action<BinaryWriter> action)
{
try
{
binaryWriter.Write((int)Command.ID);
}
catch (Exception ex)
{
if (Error != null)
Error(this, new ErrorEventArgs(ex));
}
}
Then however I couldn't specify any other parameters which I might have (such as string message).
Another possibility would be changing the parameters to type object but then the BinaryWriter
doesn't know what to access and I would have to do an explicit conversation each time. Any ideas?
I think this is fine. You can call your new method along the following lines:
SendCommand(cmd, binaryWriter => binaryWriter.DoSomething(msg));