3

Suppose I have 3 integers all declared as

int Y = 0;
int N = 0;
int U = 0;

From there I grab 2 values from a stored procedure (one string and 1 integer).
The string returns either Y,N,U
The integer returns a count of the people attending.

string test = dr["ATTEND_CDE"].ToString();
int test2 = int.Parse(dr["COUNT"].ToString());

Is there a better way to assign the corresponding integer the count other than:

if (test == "Y")
{
    Y = test2;
}
else if (test == "N")
{
    N = test2;
}
else if (test == "U")
{
    U = test2;
}
BringQBasicBack
  • 119
  • 1
  • 12
  • Just a side note: get rid of those "test" variable names before it's too late, they make the code harder to understand. – Andrew Aug 19 '15 at 17:59

3 Answers3

8

What you really have here is a mapping between a string ("Y", "N", or "U") and an int.

This is a perfect use case for a Dictionary (C# 6 syntax follows):

Dictionary<string, int> myValues = new Dictionary<string, int>()
{
    ["Y"] = 0,
    ["N"] = 0,
    ["U"] = 0
};

//usage
myValues[stringFromDatabase] = valueFromDatabase;

Note that this will throw (which is probably what you want) if the value from the database is junk.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
2

You can use a switch statement on strings. So for your example above,

switch(test)
{
    case "Y": Y = test2; break;
    case "N": N = test2; break;
    case "U": U = test2; break;
}
1

If you store Y, N, U as properties in a class then you can work with

If you use c# 6.0 then you can at least do something like

if(test.equals(nameof(y)))
{
     //...
}
Community
  • 1
  • 1
Wosi
  • 41,986
  • 17
  • 75
  • 82