Cycle and access Method's parameters value

169 views Asked by At

I have the following Method (I exemplify what I need in the comments of the method):

public static Dictionary<int, int> Foo(bool os, bool rad, bool aci, bool outr, string distrito = null)
{
    if (os == false && rad == false && aci == false && outr == false)
    {
        return new Dictionary<int, int>();
    }

    var parameters = MethodBase.GetCurrentMethod().GetParameters();
    foreach (ParameterInfo parameter in parameters)
    {
        // I would love if parameter.Value existed, because:
        // if (parameter.Value==true) {
        // x++
        // if (x == 1) string s = "true" + parameter.Name;
        // if (x > 1) s += "Additional true" + parameter.Name;
        // }
        // s += "End";
    }
    return null;
}

I have to know if one or more values of the bool parameters are true. Since they are four, imagine the combination of if I would have to do to check if only one is true, or if more than one, which are true.

So, how can I cycle the current value of the incoming Method parameters without using the parameter variable itself?

2

There are 2 answers

3
JuanR On

If you only want to know how many are true, you can turn them into integers and add their values:

var values = new[] {os, rad, aci, outr};
var sum = values.Select(v => Convert.ToInt32(v)).Sum();

If you need the name of the parameters, then you can create an anonymous object and read its properties:

public static Dictionary<int, int> Foo(bool os, bool rad, bool aci, bool outr, string distrito = null)
{
    var obj = new { os, rad, aci, outr};
    foreach (PropertyInfo pInfo in obj.GetType().GetProperties())
    {
        var value = (bool)pInfo.GetValue(obj);
        if (value)
        {
            //Do whatever you want here.                    
            Console.WriteLine("{0}: {1}", pInfo.Name, value);
        }
    }
}
0
VMAtm On

You can try some LINQ extensions, I think composition of Where and Select may be a solution, with a string.Join method on top:

// get all parameters
var parameters = MethodBase.GetCurrentMethod().GetParameters();

// for each true parameter we add this prefix
var truePrefix = "true";

// we put this string between true parameters, if more than one are present
var separator = "Additional";

// Join IEnumerable of strings with a given separator
var total = string.Join(separator, parameters
  // filter parameters to check only boolean ones, and only true ones
  .Where(p => p.ParameterType == typeof(bool) && (bool)p.Value)
  // select a name with prefix
  .Select(p => truePrefix + p.Name)))