0

Stupid question but I really can't find the answer of it. How can you insert a place holder in the the exceptions like this? And is it even possible?

  public int Age
{
    get
    {
        return this.age;
    }
    set
    {
        this.age = value;
        if((0 >= value) || (value > 100))
        {


            throw new ArgumentOutOfRangeException("The age {0}  you've entered must be in the range [1..100]",value);
        }
    }
}

2 Answers2

4

You could use string.Format with {0}, {1}...etc. placeholders:

throw new ArgumentOutOfRangeException(string.Format(
    "The age {0} you've entered must be in the range [1..100]", 
    value));
ken2k
  • 48,145
  • 10
  • 116
  • 176
0

As ArgumentOutOfRangeException expecting a string, you can't pass placeholder to it directly. To construct a string with placeholder you should use string.Format() method. Which gives the formatted string.

string message = string.Format("The age {0}  you've entered must be in the range [1..100]"  ,value);
throw new ArgumentOutOfRangeException( message );
Ishtiaq
  • 980
  • 2
  • 6
  • 21
  • 1
    Could you add some explanation to why/how this works, so that this answer is useful for future readers as well? – oɔɯǝɹ Jan 26 '15 at 11:56