View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Function without return type stands for a void function. The void function may take multiple or zero parameters and returns nothing. Here, we are going to define a method which takes 2 parameters and doesn’t return anything.
Syntax:
Example:
public static void fun1[String 1, String 2]{ // method execution code };Approach:
- Take 2 inputs into two variables.
- Pass these inputs as an argument to the function.
- Display the sum from this defined function.
Code:
Java
import java.util.*;
public class Main {
public static void main[String args[]]
{
int a = 4;
int b = 5;
calc[a, b];
}
public static void calc[int x, int y]
{
int sum = x + y;
System.out.print["Sum of two numbers is :" + sum];
}
}
Output
Sum of two numbers is :9Skip to main content
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Func Delegate
- Reference
Definition
Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
In this article
generic public delegate TResult Func[];public delegate TResult Func[];public delegate TResult Func[];type Func ExpensiveOne[]]; LazyValue lazyTwo = new LazyValue[[] => ExpensiveTwo["apple"]]; Console.WriteLine["LazyValue objects have been created."]; // Get the values of the LazyValue objects. Console.WriteLine[lazyOne.Value]; Console.WriteLine[lazyTwo.Value]; } static int ExpensiveOne[] { Console.WriteLine["\nExpensiveOne[] is executing."]; return 1; } static long ExpensiveTwo[string input] { Console.WriteLine["\nExpensiveTwo[] is executing."]; return [long]input.Length; } } class LazyValue where T : struct { private Nullable val; private Func getValue; // Constructor. public LazyValue[Func 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 */ open System type LazyValue] = let mutable value = ValueNone member _.Value = match value with | ValueSome v -> v | ValueNone -> // Execute the delegate. let v = func.Invoke[] value expensiveOne []] let lazyTwo = LazyValue[fun [] -> expensiveTwo "apple"] printfn "LazyValue objects have been created." // Get the values of the LazyValue objects. printfn $"{lazyOne.Value}" printfn $"{lazyTwo.Value}" // The example produces the following output: // LazyValue objects have been created. // // ExpensiveOne[] is executing. // 1 // // ExpensiveTwo[] is executing. // 5 Public Module Func Public Sub Main[] ' Note that each lambda expression has no parameters. Dim lazyOne As New LazyValue[Of Integer][Function[] ExpensiveOne[]] Dim lazyTwo As New LazyValue[Of Long][Function[] ExpensiveTwo["apple"]] Console.WriteLine["LazyValue objects have been created."] ' Get the values of the LazyValue objects. Console.WriteLine[lazyOne.Value] Console.WriteLine[lazyTwo.Value] End Sub Public Function ExpensiveOne[] As Integer Console.WriteLine[] Console.WriteLine["ExpensiveOne[] is executing."] Return 1 End Function Public Function ExpensiveTwo[input As String] As Long Console.WriteLine[] Console.WriteLine["ExpensiveTwo[] is executing."] Return input.Length End Function End Module Public Class LazyValue[Of T As Structure] Private val As Nullable[Of T] Private getValue As Func[Of T] ' Constructor. Public Sub New[func As Func[Of T]] Me.val = Nothing Me.getValue = func End Sub Public ReadOnly Property Value[] As T Get If Me.val Is Nothing Then ' Execute the delegate. Me.val = Me.getValue[] End If Return CType[val, T] End Get End Property End ClassRemarks
You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated 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.
Note
To reference a method that has no parameters and returns void [unit, in F#] [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 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 TestDelegate { public static void Main[] { OutputTarget output = new OutputTarget[]; WriteMethod methodCall = output.SendToFile; if [methodCall[]] Console.WriteLine["Success!"]; else Console.WriteLine["File write operation failed."]; } } 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; } } } open System.IO type WriteMethod = delegate of unit -> bool type OutputTarget[] = member _.SendToFile[] = try let fn = Path.GetTempFileName[] use sw = new StreamWriter[fn] sw.WriteLine "Hello, World!" true with _ -> false let output = new OutputTarget[] let methodCall = WriteMethod output.SendToFile if methodCall.Invoke[] then printfn "Success!" else printfn "File write operation failed." Imports System.IO Delegate Function WriteMethod As Boolean Module TestDelegate Public Sub Main[] Dim output As New OutputTarget[] Dim methodCall As WriteMethod = AddressOf output.SendToFile If methodCall[] Then Console.WriteLine["Success!"] Else Console.WriteLine["File write operation failed."] End If End Sub End Module Public Class OutputTarget Public Function SendToFile[] As Boolean Try Dim fn As String = Path.GetTempFileName Dim sw As StreamWriter = New StreamWriter[fn] sw.WriteLine["Hello, World!"] sw.Close Return True Catch Return False End Try End Function End ClassThe following example simplifies this code by instantiating the Func delegate instead of explicitly defining a new delegate and assigning a named method to it.
using System; using System.IO; public class TestDelegate { public static void Main[] { OutputTarget output = new OutputTarget[]; Func methodCall = output.SendToFile; if [methodCall[]] Console.WriteLine["Success!"]; else Console.WriteLine["File write operation failed."]; } } 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; } } } open System open System.IO type OutputTarget[] = member _.SendToFile[] = try let fn = Path.GetTempFileName[] use sw = new StreamWriter[fn] sw.WriteLine "Hello, World!" true with _ -> false let output = OutputTarget[] let methodCall = Func output.SendToFile if methodCall.Invoke[] then printfn "Success!" else printfn "File write operation failed." Imports System.IO Module TestDelegate Public Sub Main[] Dim output As New OutputTarget[] Dim methodCall As Func[Of Boolean] = AddressOf output.SendToFile If methodCall[] Then Console.WriteLine["Success!"] Else Console.WriteLine["File write operation failed."] End If End Sub End Module Public Class OutputTarget Public Function SendToFile[] As Boolean Try Dim fn As String = Path.GetTempFileName Dim sw As StreamWriter = New StreamWriter[fn] sw.WriteLine["Hello, World!"] sw.Close Return True Catch Return False End Try End Function End ClassYou can use the Func delegate with anonymous methods in C#, as the following example illustrates. [For an introduction to anonymous methods, see Anonymous Methods.]
using System; using System.IO; public class Anonymous { public static void Main[] { OutputTarget output = new OutputTarget[]; Func methodCall = delegate[] { return output.SendToFile[]; }; if [methodCall[]] Console.WriteLine["Success!"]; else Console.WriteLine["File write operation failed."]; } } 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 delegate, as the following example illustrates. [For an introduction to lambda expressions, see Lambda Expressions [VB], Lambda Expressions [C#], and Lambda Expressions [F#].]
using System; using System.IO; public class Anonymous { public static void Main[] { OutputTarget output = new OutputTarget[]; Func methodCall = [] => output.SendToFile[]; if [methodCall[]] Console.WriteLine["Success!"]; else Console.WriteLine["File write operation failed."]; } } 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; } } } open System open System.IO type OutputTarget[] = member _.SendToFile[] = try let fn = Path.GetTempFileName[] use sw = new StreamWriter[fn] sw.WriteLine "Hello, World!" true with _ -> false let output = OutputTarget[] let methodCall = Func[fun [] -> output.SendToFile[]] if methodCall.Invoke[] then printfn "Success!" else printfn "File write operation failed." Imports System.IO Module TestDelegate Public Sub Main[] Dim output As New OutputTarget[] Dim methodCall As Func[Of Boolean] = Function[] output.SendToFile[] If methodCall[] Then Console.WriteLine["Success!"] Else Console.WriteLine["File write operation failed."] End If End Sub End Module Public Class OutputTarget Public Function SendToFile[] As Boolean Try Dim fn As String = Path.GetTempFileName Dim sw As StreamWriter = New StreamWriter[fn] sw.WriteLine["Hello, World!"] sw.Close Return True Catch Return False End Try End Function End ClassThe 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 delegate. The execution of the function can then be delayed until a property that accesses the value is used in an expression. The example in the next section demonstrates how to do this.
Extension Methods
Applies to
See also
- Lambda Expressions [C# Programming Guide]
- Lambda Expressions: The fun Keyword [F#]
- Lambda Expressions
- Delegates [C# Programming Guide]
- Delegates [F#]
- Delegates in Visual Basic