tags:

views:

208

answers:

1

I am trying to understand the meaning and use of the param parameter in this line taken from a RelayCommand example:

return new RelayCommand(param => MessageBox.Show("It worked."));

First, I understand that the "param" parameter has nothing to do with the "params" keyword, is this correct?

public int Add(params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  return sum;
}

Second, what kind of delegate code do I have to add to get the following example to work?

using System;
using System.Collections.Generic;

namespace TestParam222
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The total is {0}.", Tools.GetTest(param => 23));
            Console.ReadLine();
        }
    }

    class Tools
    {
        public static string GetTest(List<int> integers)
        {
            return "ok";
        }
    }
}
+6  A: 

param isn't a keyword. It's the parameter for a lambda expression in your sample. You'd need to make your method take a delegate or an expression tree, e.g.

using System;
using System.Collections.Generic;

namespace TestParam222
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("The total is {0}.", Tools.GetTest(param => 23));
      Console.ReadLine();
    }
  }

  class Tools
  {
    public static string GetTest(Func<int, int> integers)
    {
      return "ok";
    }
  }
}

The Func<int,int> could actually be any Func<T,int> (or Func<T,long> etc) because your lambda expression doesn't use param anywhere. Alternatively it could be an Expression<Func<int,int>> etc.

I suggest you read up on lambda expressions for more details, for instance in any of these SO questions:

Jon Skeet
+1 right one, you're quick on these easy ones also, dang
bendewey