Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a variable number of named parameters to a method?

Tags:

c#

.net

I understand how to get the names of parameters passed to a method, but let's say I have a method declaration as follows:

static void ParamsTest(string template, params object[] objects)

and I want to use object/property names in my template for substitution with real property values in any of the objects in my `objects' parameter. Let's then say I call this method with:

ParamsTest("Congrats", customer, purchase);

I will only be able to retrieve two parameter names trying to fill out the template, viz, template, and objects, and the names of the objects in the objects collection are forever lost, or not?

I could require a List<object> as my second parameter, but I feel there is somehow a more elegant solution, maybe with a lambda or something. I don't know, I'm not used to using lambdas outside of LINQ.

like image 226
ProfK Avatar asked Aug 01 '10 19:08

ProfK


People also ask

How do you pass multiple parameters in a method?

Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

In what ways can you pass parameters to a method?

Parameters can be passed to a method in following three ways : Value Parameters. Reference Parameters. Output Parameters.

How do you pass variables as parameters in Python?

As you expect it, Python has also its own way of passing variable-length keyword arguments (or named arguments): this is achieved by using the **kwargs symbol. When using **kwargs, all the keywords arguments you pass to the function are packed inside a dictionary.

How do you pass a parameter to a variable?

If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword. You may also use the in keyword to pass a value parameter by reference to avoid the copy while guaranteeing that the value will not be changed.


1 Answers

Inpsired by Mark I can offer an anonymous type answer :

using System;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            ParamsTest(new { A = "a", B = "b"});
        }

        public static void ParamsTest(object o)
        {
            if (o == null)
            {
                throw new ArgumentNullException();
            }
            var t = o.GetType();
            var aValue = t.GetProperty("A").GetValue(o, null);
            var bValue = t.GetProperty("B").GetValue(o, null);
        }
    }
}

However this DOES have drawbacks :

  • No type safety. I can pass in any object
  • I can pass in an anonymous type with different members and/or types than those expected
  • You should also do more checking than in this short sample
like image 155
Andrei Rînea Avatar answered Sep 23 '22 17:09

Andrei Rînea