-4

I have the following code:

public static void MyFunc(string Title,string Artist,string Music)
{
    List<string> g = new  List<string>();
  
    if (!string.IsNullOrEmpty(Title))
    {
        g.Add( "Title " + " operator " + Title);
    }

    if (!string.IsNullOrEmpty(Artist))
    {
        g.Add("Artist " + " operator " + Artist);
    }

    if (!string.IsNullOrEmpty(Music))
    {
        g.Add("Music " + " operator " + Music);
    }
}

I want to avoid repetitive statements (in fact I have more variables (Year, Language,etc) in my real code).

How can I rewrite this code by calling 3 times the same function ?

Is it possible ? Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

create a special add function

 List<string> q= new  List<string>();
 AddString(q, "Title",Title);
 AddString(q, "Artist",Artist);
 AddString(q, "Music",Music);

public void AddString(List<string> list, string prefix, string item)
{ 
  if  ( !string.IsNullOrEmpty(item))
  {
     list.Add(prefix + " operator " + item);

   }
}

Serge
  • 40,935
  • 4
  • 18
  • 45
  • The OP don't want such a solution to this question already posted the same at https://stackoverflow.com/questions/68758010/ –  Aug 15 '21 at 12:25
  • @OlivierRogier Thank you. I don't think that it was a good idea of PO to repeat the same post again. But accidentally my code has a function that repeats 3 times as PO wanted. I am wondering what he is wanting now. – Serge Aug 15 '21 at 12:29
  • We can use `nameof` to refactor a little more (C# 6+): https://stackoverflow.com/a/68758099/12031933 –  Aug 15 '21 at 12:30
  • @OlivierRogier I was thinking about this before posting, but I was not sure that a title and a value name will always be the same. And plus it is much more effective code to put the name directly than to use reflections. – Serge Aug 15 '21 at 12:33