Expand Minimize

Func<TResult> Delegate

July 28, 2014

Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public delegate TResult Func<out TResult>()

Type Parameters

out TResult

The type of the return value of the method that this delegate encapsulates.

This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see [2678dc63-c7f9-4590-9ddc-0a4df684d42e].

Return Value

Type: TResult
The return value of the method that this delegate encapsulates.

You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.

NoteNote:

To reference a method that has no parameters and that returns void (or in Visual Basic, that is declared as a Sub rather than as a Function), use the Action delegate instead.

When you use the Func<TResult> delegate, you do not have to explicitly define a delegate that encapsulates a parameterless method. For example, the following code explicitly declares a delegate named WriteMethod and assigns a reference to the OutputTarget.SendToFile instance method to its delegate instance.


using System;
using System.IO;

delegate bool WriteMethod();

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      OutputTarget output = new OutputTarget();
      WriteMethod methodCall = output.SendToFile;
      if (methodCall())
         outputBlock.Text += "Success!" + "\n";
      else
         outputBlock.Text += "File write operation failed." + "\n";
   }
}

public class OutputTarget
{
   public bool SendToFile()
   {
      try
      {
         string fn = Path.GetTempFileName();
         StreamWriter sw = new StreamWriter(fn);
         sw.WriteLine("Hello, World!");
         sw.Close();
         return true;
      }
      catch
      {
         return false;
      }
   }
}


The following example simplifies this code by instantiating the Func<TResult> delegate rather than explicitly defining a new delegate and assigning a named method to it.


using System;
using System.IO;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      OutputTarget output = new OutputTarget();
      Func<bool> methodCall = output.SendToFile;
      if (methodCall())
         outputBlock.Text += "Success!" + "\n";
      else
         outputBlock.Text += "File write operation failed." + "\n";
   }
}

public class OutputTarget
{
   public bool SendToFile()
   {
      try
      {
         string fn = Path.GetTempFileName();
         StreamWriter sw = new StreamWriter(fn);
         sw.WriteLine("Hello, World!");
         sw.Close();
         return true;
      }
      catch
      {
         return false;
      }
   }
}


You can use the Func<TResult> delegate with anonymous methods in C#, as the following example illustrates.


using System;
using System.IO;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      OutputTarget output = new OutputTarget();
      Func<bool> methodCall = delegate() { return output.SendToFile(); };
      if (methodCall())
         outputBlock.Text += "Success!" + "\n";
      else
         outputBlock.Text += "File write operation failed." + "\n";
   }
}

public class OutputTarget
{
   public bool SendToFile()
   {
      try
      {
         string fn = Path.GetTempFileName();
         StreamWriter sw = new StreamWriter(fn);
         sw.WriteLine("Hello, World!");
         sw.Close();
         return true;
      }
      catch
      {
         return false;
      }
   }
}


You can also assign a lambda expression to a Func<T, TResult> delegate, as the following example illustrates.


using System;
using System.IO;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      OutputTarget output = new OutputTarget();
      Func<bool> methodCall = () => output.SendToFile();
      if (methodCall())
         outputBlock.Text += "Success!" + "\n";
      else
         outputBlock.Text += "File write operation failed." + "\n";
   }
}

public class OutputTarget
{
   public bool SendToFile()
   {
      try
      {
         string fn = Path.GetTempFileName();
         StreamWriter sw = new StreamWriter(fn);
         sw.WriteLine("Hello, World!");
         sw.Close();
         return true;
      }
      catch
      {
         return false;
      }
   }
}


The underlying type of a lambda expression is one of the generic Func delegates. This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate. In particular, because many methods of types in the System.Linq namespace have Func parameters, you can pass these methods a lambda expression without explicitly instantiating a Func delegate.

If you have an expensive computation that you want to execute only if the result is actually needed, you can assign the expensive function to a Func<TResult> delegate. The execution of the function can then be delayed until a property that accesses the lazy value is used in an expression. The example in the next section demonstrates how to do this.

The following example demonstrates how to use a delegate that takes no parameters. This code creates a generic class named LazyValue that has a field of type Func<TResult>. This delegate field can store a reference to any function that returns a value of the type that corresponds to the type parameter of the LazyValue object. The LazyValue type also has a Value property that executes the function (if it has not already been executed) and returns the resulting value.

The example creates two methods and instantiates two LazyValue objects with lambda expressions that call these methods. The lambda expressions do not take parameters because they just need to call a method. As the output shows, the two methods are executed only when the value of each LazyValue object is retrieved.


using System;

static class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Note that each lambda expression has no parameters.
      LazyValue<int> lazyOne = new LazyValue<int>(() => ExpensiveOne(outputBlock));
      LazyValue<long> lazyTwo = new LazyValue<long>(() => ExpensiveTwo(outputBlock, "apple"));

      outputBlock.Text += "LazyValue objects have been created." + "\n";

      // Get the values of the LazyValue objects.
      outputBlock.Text += lazyOne.Value + "\n";
      outputBlock.Text += lazyTwo.Value + "\n";
   }

   static int ExpensiveOne(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.Text += "\nExpensiveOne() is executing." + "\n";
      return 1;
   }

   static long ExpensiveTwo(System.Windows.Controls.TextBlock outputBlock, string input)
   {
      outputBlock.Text += "\nExpensiveTwo() is executing." + "\n";
      return (long)input.Length;
   }
}

class LazyValue<T> where T : struct
{
   private Nullable<T> val;
   private Func<T> getValue;

   // Constructor.
   public LazyValue(Func<T> func)
   {
      val = null;
      getValue = func;
   }

   public T Value
   {
      get
      {
         if (val == null)
            // Execute the delegate.
            val = getValue();
         return (T)val;
      }
   }
}
/* The example produces the following output:

    LazyValue objects have been created.

    ExpensiveOne() is executing.
    1

    ExpensiveTwo() is executing.
    5
*/


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft