Is it possible to loop through a function arguments to check if any of them is null(or check them by another custom function)? something like this:
public void test (string arg1, string arg2, object arg3, DataTable arg4)
{
foreach (var item in argus)
{
if( item == null)
{
throw;
}
}
// do the rest...
}
what is the correct keyword for "argus"? I know that this is possible by some more if statement but looking for a faster way...
You could use the params keyword to loop through all arguments but then you would use their type in the method itself. I would write a utility function that checks for null.
public void CheckForNullArguments(params object[] args)
{
foreach (object arg in args)
if (arg == null) throw new ArgumentNullException();
}
You can call this at the start of your method like
CheckForNullArguments(arg1, arg2, arg3, arg4);
I suppose you don't want to change to params each method in your project(s). You can use PostSharp, but there are other methods, depends on your framework.
using System;
using System.Data;
using System.Reflection;
using PostSharp.Aspects;
namespace TestAOP
{
class Program
{
static void Main(string[] args)
{
SomeClass someInstance = new SomeClass();
someInstance.test(null, null, null, null);
}
}
public class SomeClass
{
[CheckForNulls]
public void test(string arg1, string arg2, object arg3, DataTable arg4)
{
// do the rest...
}
}
[Serializable]
public class CheckForNullsAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
ParameterInfo[] parameters = args.Method.GetParameters();
for (int i = 0; i < args.Arguments.Count; i++)
{
if (args.Arguments[i] == null)
throw new ArgumentNullException(parameters[i].Name);
}
}
}
}
http://www.sharpcrafters.com/ to get PostSharp, also you can find doc there.
If you want an easy way to loop through arguments, you should think about using the params keyword
public void test (params object args[])
{
foreach(var argument in args)
{
if(item == null)
{
throw new ArgumentNullException();
}
}
}
Other than that you could use reflection, but it seems you don't need it that badly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With