c# 4.0 nullable input parameters to a method
public IQueryable<Profile> FindAllProfiles(string CountryFrom, string CountryLoc)
{
....
}
For the above method, is it possible to have nullable input parameters CountryFrom an开发者_StackOverflow社区d CountryLoc? When I call this method, I have to pass in the 2 values otherwise I may get exceptions. Any ideas..?
If you're writing the method and using C# 4, you can use optional arguments.
With it, you can put a default value for the arguments.
If you're just using the function, then you can pass-in String.Empty instead of a null string.
As others have said, string
can already be null....
Since you're using a string
, you'll need to test against string.IsNullOrEmpty(yourString)
before using the parameter, to verify a value actually exists.
You need to check the strings at entry, using IsNullOrEmpty
is probably the best approach (unless an empty string ("") is valid), you could then return a null or set defaults and process onward or even throw your own exception (and catch it in your calling routine).
I'd be tempted to say that if you have a method call that you know cannot accept null parameters that you check before you call the method and handle that within your calling class.
string
is nullable. Did you mean non-nullable?
string
is a reference type, and hence already nullable. You can call FindAllProfiles(null, null)
and the code will at least compile fine. Of course, you need to insure the method body appropiately handles null parameters, but that's ancillary.
Alternatively, if you just want to disallow calling the FindAllProfiles
function with any null parameters at runtime (do you?), just use guard statements at the top of the method as such:
if (CountryFrom == null)
throw new ArgumentNullException("CountryFrom")
if (CountryTo == null)
throw new ArgumentNullException("CountryTo")
Side note: function parameter names should be written in camelCase according to all style guidelines.
Your question asks if they can be nullable, yet it seems to imply that they must not be null.
Because string
is a reference type, they are nullable (and must be nullable). There is no way to enforce (at compile time) that they have a non-null value.
精彩评论