I have a function that is getting passed a String and a DataRow.
The String is a custom formatter. The idea is to do this
String.Format(passed_in_String, DataRow("ColumnINeed"))
The reason this is being done is at this point we have no idea what the column contains.
However, if the formatter is “{0:MM/dd/yyyy}” and the DataRow(“ColumnINeed”) is an integer containing 42, String.Format is returning: MM/dd/yyyy
In this situation I need it to throw an exception instead of returning nonsense.
Is there anyway to make String.Format throw an exception if the object does not match what the format string is expecting?
You need to become familiar with your data. If you’re in a situation where the data could truly be anything at anytime, you’re in a bad spot. Frankly, I rather doubt you are in that situation. At least, I’m extremely hopeful you are not.
If it is exceptional for the data in the column to not be a date, then pull it out as a date. Don’t pull it out and hope it nicely formats to one, pull it out as one!
Even if you find your data to be stringly typed, immediately parse it. Set the expectation that the value is a date in your code. When it isn’t, it will create an exception.
Edit: Chris mentions a good alternate suggestion in the comments. You can also write
The benefit here is what if the column allowed nulls?
Here, you may get “Specified Cast Not Valid” if row holds DBNull.
This alternate handles DBNull appropriately.