Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a value into an Exception String Message

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading