I am working on a project where I need to switch for example between device types. I want to define them like in C/C++. I found out that this is not possible in C# the same way. I am making some experimental code to learn how it works, but I am stuck on one thing. I’ve pointed that out in the code below. Please take a look :). I hope the idea of my code is clear, how should I change it to make it work?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
productnames pn = new productnames();
string str = textBox1.Text;
switch (pn) // I am getting an red line under pn; which says: A switch expression or case label must be a bool, char, string, integral, enum or corresponding nullable type
{
case DEVICE1:
label1.Text = str+"CASE1";
break;
case DEVICE2:
label1.Text = str+"CASE2";
break;
}
}
}
public class productnames
{
public const string DEVICE1 = "name1";
public const string DEVICE2 = "name2";
public const string DEVICE3 = "name3";
public const string DEVICE4 = "name4";
}
The code above does not work, because you can not switch between an entire class. A better approach would be something like this:
private const string DEVICE1 = "dev1";
private const string DEVICE2 = "dev2";
private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
getCommand(str)
}
private void getCommand(string Dev)
{
switch (Dev)
{
case DEVICE1:
label1.Text = str+"CASE1";
break;
case DEVICE2:
label1.Text = str+"CASE2";
break;
}
}
This example could be useful:
#define CMD_VERSION 0
#define CMD_TYPE 1
private void getCommandName(CMD)
{
switch(CMD)
{
case CMD_VERSION:
return ("ver");
case CMD_TYPE:
return ("serienummer");
}
}
Let’s be creative and add an example that would be used more quickly in real life.
[Edit]
Seems i was going in the right direction, only your “define” example give them integer’s (which they have anyway on default in the order you have declared them in).
But to follow your example it would be something like: