Search code examples
c#custom-exceptions

C# Placeholders in Exceptions


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);
        }
    }
}

Solution

  • 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));