c# - Nicer way of parameter checking? -
With C # 3.0, we use the .NET 2.0 framework (I think this is the last version of C # that can run on 2.0 version.
correct me if I'm wrong).
Is there something created in C # that makes this type of parameter validation more convenient?
Public connection settings (string url, string username, string password, ball check permissions) {if (username == faucet) {new permutation fee exception ("username"); } If (password == faucet) {new argument (NullException) ("password"); } If (string.isnllquite (url)) {new logic expansion ("should not be empty or empty, it was" + (url == blank url: "blank"), "url"); } This.url = url; This.username = Username; This.password = password; This.checkPermissions = check chapter; }
Such parameter verification becomes a normal pattern and many "almost boilerplate" codes are dropped into our public ways.
If nothing has been made. Is there any great free library that we can use?
I usually have static support methods ...
example
public static zero CheckNotNull (object value, string parameter name) {if (value == null) {new ArgumentNullException (parameterName); }}
This means that you can compress your code to anything given below and make it a bit tidier.
CheckNotNull (user name, "username"); CheckNotal (password, "password");
Or you can wrap it as an extension method:
public static zero checkNotNull & lt; T & gt; (This T value, string parameter name) {if (value == faucet) {New argument NullException (parameter name); }}
and experiment like this:
username.CheckNotNull ("user name"); Password.CheckNotNull ("password");
And if you are feeling really fancy, you can probably query the parameter names using the reflection. The reflection is slightly slow, so you only want to do this if you are throwing an exception, but it prevents you from typing literal parameter names all the time.
Comments
Post a Comment