0
string q1 = "What  Company during the {0}, {1},{2},{3}  tax years?"
q1 = string.Format(q1, model.CurYear, model.Year2, model.Year3, model.Year4);

Here comes I may have year2,year3,year4 or not it may contain null. so is there any scope of having optional parameters. Error message:I am getting you are having more arguments list,so is there any solution.

0

5 Answers 5

0

You could check for null and use a ternary operation to replace null for string.empty. Otherwise, check for null values before and use a different format string for each case

Sign up to request clarification or add additional context in comments.

Comments

0

You should check if the string is null and put string.Empty, but you should include the comma in year text; if you don't, you'll get a text like "What Company during the {0},,,{3} tax years?"

Comments

0

You can use the null-coalescing operator (??) like this:

string a = null;
string b = "smthing";
string c = "nothing?";
string d = null;
string someString = string.Format
       ("this is a string with \"optional\" parameters {0} {1} {2} {3}",
       a ?? "",
       b ?? "",
       c ?? "",
       d ?? "");

It does the following:
Use its own value, except if null then use value to the right of ??

This is a generelised answer however, you need ,'s so you would have to build the string in some manner.

Comments

0

You can all additional readonly property inside model to collect all years as a list/whatever and use this list to get all not-null years.

Something like:

class YourModelClass
{
    public int? Year2 { get; set; }
    public int? Year3 { get; set; }
    public int? Year4 { get; set; }

    public List<int?> Years => new List<int?> {Year2, Year3, Year4};
}

    YourModelClass model = new YourModelClass();
    string result = $"What  Company during the {string.Join(",", model.Years.Where(a => a != null).ToList())} tax years?";

Comments

0

There are 3 things:

  1. Format the string with changing years.

    string format = "What  Company during the {0} tax years?"
    q1 = string.Format(format, yearsList);
    
  2. Filter list(not .net List) of years.

    years = new []{model.CurYear, model.Year2, model.Year3, model.Year4]
                  .Where(y => y != null);
    
  3. Join year string by ','.

    yearsList = String.Join(", ", years);
    

Put them together:

  q1 = String.Format(
      "What  Company during the {0} tax years?", 
      String.Join(
          ", ", 
          new []{model.CurYear, model.Year2, model.Year3, model.Year4]
              .Where(y => y!=null))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.