Chris O'Brien

I have a general question about what is common practice for a problem below. Let's say I have a method that has a few parameters, and I want to validate these parameters before executing method's operations. For example,

public string GetData(string ticker, DateTime startDate, DateTime endDate, char frequency)
{
if (string.IsNullOrEmpty(ticket))
// Invalid, cannot continue
else if (startDate <= endDate)
// Invalid, cannot continue
else if (frequency != 'd' && frequency != 'w' && frequency != 'm')
// Invalid, cannot continue

// Actually do stuff now that the parameters have been validated
}


Now, where I've commented "Invalid, cannot continue", I'd like to know how people would handle this.

Should I return null Or should I return string.Empty I know from experience that it's always best to return empty arrays or empty objects when a method returns an array or other object and errors. But also, when one does something like QueryString["nonexistentKey"] where just a string is returned, null is returned if nonexistentKey doesn't exists.

Also, if I just return null or an empty string, that doesn't tell the developer what's wrong. What if I want to return or display some sort of custom error message Is it best to Debug.WriteLine(errorMessage) before returning, or is there a better way


Re: Visual C# General Best way to handle invalid parameters in method

Nayan Paregi

Hi

Best way to throw an argument exeception when u get the invalid parameter from the user.

For Example.

Code Snippet

throw new ArgumentException("Invalid Parameter", "Parameter name");






Re: Visual C# General Best way to handle invalid parameters in method

Chris O'Brien

Really I thought exceptions were only suppose to be used for exceptional circumstances. Didn't think invalid parameters warranted it. But since there is an ArgumentException, that makes sense.




Re: Visual C# General Best way to handle invalid parameters in method

Nayan Paregi

Yes argumentexeception make sence. if a user given invalid paramater to the method.




Re: Visual C# General Best way to handle invalid parameters in method

Nayan Paregi

Hi,

If ur problem has been resolved or answered, request you to change the status of problem n mark it to resolved/completed.

Thanks