Home > Mobile >  C#: how assign a value to a string var without using switch
C#: how assign a value to a string var without using switch

Time:04-17

First of all I must say that I am pretty new using C#. I have written this code block to assign a value to a string var depending on the value of another var. I have used the Switch statement:

    switch (_reader.GetString(0))
    {
       case "G":
            permiso.Area = "General";
            break;
       case "SIS":
            permiso.Area = "Sistems";
            break;
       case "SOP":
            permiso.Area = "Development";
            break;
       case "HLP":
            permiso.Area = "Support";
            break;
       }

Can I make this in an easier way in C#? Thanks!

CodePudding user response:

You can use Dictionary<string, string>(), which can store your "switch case" string as key and "switch case value" in value.

Example:

var dict = new Dictionary<string, string>()
{
  {"G", "General"},
  {"SIS", "Sistems"},
  ...
}
So your code in order to access will be: 
var key = _reader.GetString(0);
if(dict.TryGetValue(key, out var value)
{
   permiso.Area = value;
}
else
{
  // handle not exists key situation
}

CodePudding user response:

Modern C# has a pattern matching switch

permiso.Area = _reader.GetString(0) switch {
  "G" => "General",
  "SIS" => "Sistems",
  "SOP" => "Development",
  "HLP" => "Support",
  _ => throw new InvalidOperationException($"The value {_reader.GetString(0)} is not handled")
};

C# will complain at you if you don't include the "else" at the end _ =>

CodePudding user response:

I mean if exists in C# somo sentence that makes something like that: my_string=my_string.decode(old_value0,new_value0, old_value1,new_value1, ...)

If you're after something like Oracle's DECODE, you can write it:

string Decode(string expr, params string[] arr){

  for(int i = 0; i < arr.Length; i =2)
    if(arr[i] == expr)
      return arr[i 1];
  return arr.Length % 2 == 0 ? null : arr[arr.Length-1];
}

You'd use it like:

permiso.Area = Decode(reader.GetString(0), "G", "General", "SIS", "Sistems", "SOP", "Development", "HLP", "Support");

If you want an ELSE, pass an odd length array (something after the "Support")

If you want to be able to call it on a string, such as reader.GetString(0).Decode("G" ...) you can declare it in a static class and precede the first argument with this :

static string Decode(this string expr, ....)

That will make it an extension method, so it can be called "on a string"

  • Related