Mark
Mark

Reputation: 5028

C# make a constant array, then use it

I'm quite new to C#. I have found several workarounds for my goal, but I'm asking the best way to do it, using the native functions of the framework.

Let's say I have to develop a communication protocol. I need to store a constant (ready-only) array for the desired functions. I.e.:

public static readonly IReadOnlyList<byte> CMD1 = new byte[] { 0x03, 0x55 };

Later, I would define a SendCommand function that needs to take the correct command, complete it with parameters and checksum. Something like this:

List<byte> msg = Commands.CMD1.ToList(); // <-- DOESN'T WORK
msg.Add(some_parameter);
msg.Add(checksum(msg));
serialPort.Write(msg.ToArray(), 0, msg.Count);

Here:

https://msdn.microsoft.com/it-it/library/hh192385(v=vs.110).aspx

it seems the ToList() method is available for the IReadOnlyList interface, but the compiler doesn't accept it.

Two questions:

  1. why I cannot use the ToList() method here?
  2. is there a better approach?

Upvotes: 1

Views: 2099

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156948

This code seems to be off very much. You are converting a read-only list to a new list, then back to an array.

Why not use arrays from the start and rely on the underlying interfaces for the rest? You might want to use IEnumerable<byte> for example for your checksum method, or use byte array from the start.

public static readonly byte[] CMD1 = new byte[] { 0x03, 0x55 };

List<byte> msg = new List<byte>(CMD1);
msg.Add(some_parameter);
msg.Add(checksum(msg));
serialPort.Write(msg, 0, msg.Length);

Upvotes: 3

Dekay
Dekay

Reputation: 111

Why don't you put you commands in an enumeration, so you can select them by name. You won't have to remember them all.

public enum CommandsEnum
{
    Com1 = 0x03,
    Com2 = 0x05
}

Then you can easily add them in collections and use them everywhere

var cmds = new List<byte>();

cmds.Add((byte)CommandsEnum.Com1);
cmds.Add((byte)CommandsEnum.Com1);

serialPort.Write(cmds.ToArray(), 0, cmds.Count);

Upvotes: 0

Related Questions