Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Using foreach to loop through method arguments

Tags:

c#

.net

foreach

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...

like image 955
Farhad Avatar asked Jul 24 '11 13:07

Farhad


3 Answers

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);
like image 112
Bjorn Coltof Avatar answered Oct 13 '22 19:10

Bjorn Coltof


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.

like image 44
Adrian Iftode Avatar answered Oct 13 '22 20:10

Adrian Iftode


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

like image 6
bevacqua Avatar answered Oct 13 '22 19:10

bevacqua