how to implement Action<..> as Func<...> - c#

I'd like to implement Action as func and get the error : could not use void in this context.
Please advise
Action<string> someFunc_1 = Console.WriteLine;
someFunc_1("Test");
Func<string, void> someFunc_2 = Console.WriteLine;

Action<T1, T2, ...> is done to replace Func<T1, T2, ..., void>.
You can't use void in a generic. It's not a type in C#.
Then in your case, use Action<string> instead of Func<string, void>.

Func<string, bool> someFunc_2 = s =>
{
Console.WriteLine(s);
return true;
};

Related

Is it possible to cast Func<object, object> to Func<T1, TResult> using reflection without Reflection.Emit

I am trying to create an implementation of Autofac-style automatic delegate factories that would work with AOT (specifically, Unity3d and IL2CPP).
Main problem that I ran into is inability to cast from Func<object, object> to Func<T1, TResult> in the runtime.
Is there any way you can do that with reflection, but avoiding generating IL code in the runtime (i.e. without Reflection.Emit)?
Func<object, object> func = delegate (object arg1)
{
return arg1.ToString() + " bar";
};
Func<string, string> func2;
func2 = (Func<string, string>)func;
Console.WriteLine(func2("foo")); // "foo bar" ? :(
// System.InvalidCastException: Unable to cast object of type 'System.Func`2[System.Object,System.Object]' to type 'System.Func`2[System.String,System.String]'.
I don't believe it's possible to cast a Func of one type to a Func of another type. Depending on the use case, you could wrap one in the other to achieve your desired result, as demonstrated below.
Func<object, object> func = delegate (object arg1)
{
return arg1.ToString() + " bar";
};
// Wrap func with a call by func2 to get the desired casting.
Func<string, string> func2 = o => func(o) as string;
Console.WriteLine(func2("foo"));

Can a lambda expression be declared and invoked at the same time in C#?

In VB.NET, a lambda expression can be declared and invoked on the same line:
'Output 3
Console.WriteLine((Function(num As Integer) num + 1)(2))
Is this possible in C#?
You have to tell the compiler a specific delegate type. For example, you could cast the lambda expression:
Console.WriteLine(((Func<int, int>)(x => x + 1))(2));
EDIT: Or yes, you can use a delegate creation expression as per Servy's answer:
Console.WriteLine(new Func<int, int>(i => i + 1)(2));
Note that this isn't really a normal constructor call - it's special syntax for delegate creation which looks like a regular constructor call. Still clever though :)
You can make it slightly cleaner with a helper class:
public static class Functions
{
public static Func<T> Of<T>(Func<T> input)
{
return input;
}
public static Func<T1, TResult> Of<T1, TResult>
(Func<T1, TResult> input)
{
return input;
}
public static Func<T1, T2, TResult> Of<T1, T2, TResult>
(Func<T1, T2, TResult> input)
{
return input;
}
}
... then:
Console.WriteLine(Functions.Of<int, int>(x => x + 1)(2));
Or:
Console.WriteLine(Functions.Of((int x) => x + 1)(2));
Console.WriteLine(new Func<int, int>(i => i + 1)(2));
Uses a few less parentheses to use the Func's constructor than a cast.
Yes, though it's messy:
Console.WriteLine(((Func<int, int>) (num => num + 1))(2));
Kind or, you would have to use the Func object :
var square = new Func<double, double>(d => d*d)(2);
Console.WriteLine(square);

How do I describe an Action<T> delegate that returns a value (non-void)?

The Action<T> delegate return void. Is there any other built-in delegate which returns non void value?
Yes. Func<> returns the type specified as the final generic type parameter, such that Func<int> returns an int and Func<int, string> accepts an integer and returns a string. Examples:
Func<int> getOne = () => 1;
Func<int, string> convertIntToString = i => i.ToString();
Action<string> printToScreen = s => Console.WriteLine(s);
// use them
printToScreen(convertIntToString(getOne()));
Sure, the Func Delegates return T.
Func<TResult> is "TResult method()"
Func<TInput, TResult> is "TResult method(TInput param)"
All the way down to
Func<T1, T2, T3, T4, TResult>
http://msdn.microsoft.com/en-us/library/bb534960.aspx
http://msdn.microsoft.com/en-us/library/bb534303.aspx
Also, for the sake of completeness, there is Predicate which returns bool.
Predicate<T> is "bool method(T param)"
http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx

How to declare a generic delegate with an out parameter [duplicate]

This question already has answers here:
Func<T> with out parameter
(4 answers)
Closed 9 years ago.
Func<a, out b, bool>, just don't compile, how to declare that i want the second parameter be an out one?
I want to use it like this:
public class Foo()
{
public Func<a, out b, bool> DetectMethod;
}
Actually, Func is just a simple delegate declared in the .NET Framework. Actually, there are several Func delegates declared there:
delegate TResult Func<TResult>()
delegate TResult Func<T, TResult>(T obj)
delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, T3, TResult>(T1 obj1, T2 obj2, T3 obj3)
delegate TResult Func<T1, T2, T3, T4, TResult>(T1 obj1, T2 obj2, T3 obj3, T4 obj4)
delegate TResult Func<T1, T2, ... , T16, TResult>(T1 obj1, T2 obj2, ..., T16 obj16)
So the only thing you can do is declare your custom delegate:
delegate bool MyFunc<T1, T2>(T1 a, out T2 b)
You need to make your own delegate type, like this:
delegate bool MyFunc(Type1 a, out Type2 b);
You might want to rethink your design. Do you really need to complicate your code by adding an out parameter?
You can wrap the bool return type and the second out type in their own class (or .NET 4.0 Tuple) and use that as a return type:
public Func<Type1, Tuple<Type2, bool>> DetectMethod;
Of course when you want to use the delegates to reference try-parse methods, you are on the right track and you'll need to define a new delegate as others already described.

Func<T> with out parameter

Can I pass a method with an out parameter as a Func?
public IList<Foo> FindForBar(string bar, out int count) { }
// somewhere else
public IList<T> Find(Func<string, int, List<T>> listFunction) { }
Func needs a type so out won't compile there, and calling listFunction requires an int and won't allow an out in.
Is there a way to do this?
ref and out are not part of the type parameter definition so you can't use the built-in Func delegate to pass ref and out arguments. Of course, you can declare your own delegate if you want:
delegate V MyDelegate<T,U,V>(T input, out U output);
Why not create a class to encapsulate the results?
public class Result
{
public IList<Foo> List { get; set; }
public Int32 Count { get; set; }
}
The Func family of delegates (or Action for that matter) are nothing but simple delegate types declared like
//.NET 4 and above
public delegate TResult Func<out TResult>()
public delegate TResult Func<in T, out TResult>(T obj)
//.NET 3.5
public delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 obj1, T2 obj2, T3 obj3)
etc. Delegates as such can have out/ref parameters, so in your case its only a matter of custom implementation by yourself as other answers have pointed out. As to why Microsoft did not pack this by default, think of the sheer number of combinations it would require.
delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, TResult>(out T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, TResult>(T1 obj1, out T2 obj2)
delegate TResult Func<T1, T2, TResult>(out T1 obj1, out T2 obj2)
for just two parameters. We have not even touched ref. It would actually be cumbersome and confusing for developers.
You could wrap it in a lambda/delegate/function/method that exposed the right interface and called FindForBar, but I suspect that FindForBar has count as an out parameter as a reason, so you'd need to be sure throwing that information away was ok/safe/desirable/had the right results (you'd need to be sure of this even if you could just directly pass in FindForBar).

Categories