Why can’t I add a variable value into a string using this code:
throw new ArgumentOutOfRangeException("Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {0}",value);
The error I get is: "CS1503: Argument 2: Cannot convert from ‘int’ to ‘System.Exception?’"
But when I use this code it works fine:
throw new ArgumentOutOfRangeException($"Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {value}");
Can somebody help me understand why? As far as I know these two ways of doing it should result with the same end. I don’t understand why it would be converting, shouldn’t I then get the same error if I use a console.WriteLine method? What makes this special?
>Solution :
The first syntax only works for methods that use format strings. Some methods, like Console.WriteLine, have an overload that takes a format string as the first argument and any number of objects as a subsequent arguments array, so you’re probably used to it working the same as when you use string interpolation syntax ($"...").
Most exception constructors don’t follow that pattern, so you’ll have to build your own string to pass in as their message argument. String interpolation syntax will do that for you automatically, as you’ve discovered. Or you can call string.Format explicitly:
throw new ArgumentOutOfRangeException(
string.Format(
"Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {0}",
value));