Refactor and Remove Duplication From this Memoization Code - c#

I'm trying to remove some duplication from this code, and have it easily support functions with more parameters.
How would you improve this code and allow for more complex functions?
Also, I'm worried about my key generation, some objects won't serialize to a string distinctly, and just return their typename, not a unique value. Suggestions?
Edit: I've used ChaosPandion's answer, and got it down to this
using System;
using System.Web.Caching;
public static class Memoize
{
public static Cache LocalCache = System.Web.HttpRuntime.Cache ?? System.Web.HttpContext.Current.Cache;
public static TResult ResultOf<TArg1, TResult>(Func<TArg1, TResult> func, long durationInSeconds, TArg1 arg1)
{
var key = HashArguments(func.Method.Name, arg1);
return ResultOf(key, durationInSeconds, () => func(arg1));
}
public static TResult ResultOf<TArg1, TArg2, TResult>(Func<TArg1, TArg2, TResult> func, long durationInSeconds, TArg1 arg1, TArg2 arg2)
{
var key = HashArguments(func.Method.Name, arg1, arg2);
return ResultOf(key, durationInSeconds, () => func(arg1, arg2));
}
public static TResult ResultOf<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, TResult> func, long durationInSeconds, TArg1 arg1, TArg2 arg2, TArg3 arg3)
{
var key = HashArguments(func.Method.Name, arg1, arg2, arg3);
return ResultOf(key, durationInSeconds, () => func(arg1, arg2, arg3));
}
public static TResult ResultOf<TArg1, TArg2, TArg3, TArg4, TResult>(Func<TArg1, TArg2, TArg3, TArg4, TResult> func, long durationInSeconds, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4)
{
var key = HashArguments(func.Method.Name, arg1, arg2, arg3, arg4);
return ResultOf(key, durationInSeconds, () => func(arg1, arg2, arg3, arg4));
}
private static TResult ResultOf<TResult>(string key, long durationInSeconds, Func<TResult> func)
{
return LocalCache.Get(key) != null
? (TResult)LocalCache.Get(key)
: CacheResult(key, durationInSeconds, func());
}
public static void Reset()
{
var enumerator = LocalCache.GetEnumerator();
while (enumerator.MoveNext())
LocalCache.Remove(enumerator.Key.ToString());
}
private static T CacheResult<T>(string key, long durationInSeconds, T value)
{
LocalCache.Insert(key, value, null, DateTime.Now.AddSeconds(durationInSeconds), new TimeSpan());
return value;
}
private static string HashArguments(params object[] args)
{
if (args == null)
return "noargs";
var result = 23;
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg == null)
{
result *= (31 * i + 1);
continue;
}
result *= (31 * arg.GetHashCode());
}
return result.ToString();
}
}

Here is my version which removes quite a bit of duplication and should produce a much more reliable range of keys.
EDIT
My latest version produces a pretty reliable distribution. Take a look at the example I placed in the Main method.
class Program
{
public static class Memoize
{
public static Cache LocalCache =
System.Web.HttpRuntime.Cache ?? System.Web.HttpContext.Current.Cache;
public static TResult ResultOf<TArg1, TResult>(
Func<TArg1, TResult> func,
TArg1 arg1,
long durationInSeconds)
{
var key = HashArguments(
func.Method.DeclaringType.GUID,
typeof(TArg1).GUID,
(object)arg1);
return Complete(key, durationInSeconds, () => func(arg1));
}
public static TResult ResultOf<TArg1, TArg2, TResult>(
Func<TArg1, TArg2, TResult> func,
TArg1 arg1,
TArg2 arg2,
long durationInSeconds)
{
var key = HashArguments(
func.Method.DeclaringType.GUID,
typeof(TArg1).GUID,
(object)arg1,
typeof(TArg2).GUID,
(object)arg2);
return Complete(key, durationInSeconds, () => func(arg1, arg2));
}
public static TResult ResultOf<TArg1, TArg2, TArg3, TResult>(
Func<TArg1, TArg2, TArg3, TResult> func,
TArg1 arg1,
TArg2 arg2,
TArg3 arg3,
long durationInSeconds)
{
var key = HashArguments(
func.Method.DeclaringType.GUID,
typeof(TArg1).GUID,
(object)arg1,
typeof(TArg2).GUID,
(object)arg2,
typeof(TArg3).GUID,
(object)arg3);
return Complete(key, durationInSeconds, () => func(arg1, arg2, arg3));
}
public static void Reset()
{
var enumerator = LocalCache.GetEnumerator();
while (enumerator.MoveNext())
LocalCache.Remove(enumerator.Key.ToString());
}
private static T CacheResult<T>(string key, long durationInSeconds, T value)
{
LocalCache.Insert(
key,
value,
null,
DateTime.Now.AddSeconds(durationInSeconds),
new TimeSpan());
return value;
}
static T Complete<T>(string key, long durationInSeconds, Func<T> valueFunc)
{
return LocalCache.Get(key) != null
? (T)LocalCache.Get(key)
: CacheResult(key, durationInSeconds, valueFunc());
}
static string HashArguments(params object[] args)
{
if (args == null)
return "null args";
int result = 23;
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg == null)
{
result = 31 * result + (i + 1);
continue;
}
result = 31 * result + arg.GetHashCode();
}
return result.ToString();
}
}
static int test(int a, int b)
{
return a + b;
}
private static class Inner
{
public static int test(int a, int b)
{
return a + b;
}
}
static int test(int a, object b)
{
return a + (int)b;
}
static void Main(string[] args)
{
Memoize.ResultOf<int, int, int>(test, 1, 2, 100000);
Memoize.ResultOf<int, int, int>(test, 2, 1, 100000);
Memoize.ResultOf<int, int, int>(Inner.test, 1, 2, 100000);
Memoize.ResultOf<int, int, int>(Inner.test, 2, 1, 100000);
Memoize.ResultOf<int, object, int>(test, 1, 2, 100000);
Memoize.ResultOf<int, object, int>(test, 2, 1, 100000);
}
}

The basic idea in ChaosPandion's code is correct, but there are some fatal flaws that must be fixed in order for this to work reliably.
1) Rather than using a hash of hashes, you need to make a genuinely unique key. One way would be to concatenate the string representations of each element in the parameter array, with a delimiter. This way, once a result has been memoized, it will consistently be retrieved, without false positives.
Chaos' trick with the GUID of the method is useful here, but this avoids the problem of depending on GetHashCode being truly unique as well as counting on a fairly simple hash of hashes to remain unique. Instead, the full string will get hashed, but there will be a full character-by-character comparison to rule out mismatches.
Admittedly, concatenating a big string is not particularly elegant and might even impact performance. Moreover, this still leaves you with the issue of classes whose ToString does not give instance-specific information. However, there are solutions for this based on reflection.
2) A very simple optimization would be to call LocalCache.Get just once in Complete. This is a potentially expensive operation, so there's really no excuse for doubling the cost.
Other than that, go with what ChaosPandion suggested.

Related

Implementing the Choice Type in C#

for educational reasons I'm trying to implement the Choice and the Option Type from F# in C#. This was inspired by the book "Real World Functional Programming" and some blog posts like: http://bugsquash.blogspot.de/2011/08/refactoring-to-monadic-c-applicative.html and http://tomasp.net/blog/idioms-in-linq.aspx/.
I would like to get this to work, but I don't know how to implement the Extensions for the Choice Type (Bind, Map, SelectMany, ...):
public static void Division()
{
Console.WriteLine("Enter two (floating point) numbers:");
(
from f1 in ReadDouble().ToChoice("Could not parse input to a double.")
from f2 in ReadDouble().ToChoice("Could not parse input to a double.")
from result in Divide(f1, f2).ToChoice("Cannot divide by zero.")
select result
)
.Match(
x => Console.WriteLine("Result = {0}", x),
x => Console.WriteLine("Error: {0}", x));
}
public static Option<double> Divide(double a, double b)
{
return b == 0 ? Option.None<double>() : Option.Some(a / b);
}
public static Option<Double> ReadDouble()
{
double i;
if (Double.TryParse(Console.ReadLine(), out i))
return Option.Some(i);
else
return Option.None<double>();
}
public static Option<int> ReadInt()
{
int i;
if (Int32.TryParse(Console.ReadLine(), out i))
return Option.Some(i);
else
return Option.None<int>();
}
}
The Option Type looks like this:
public enum OptionType
{
Some, None
}
public abstract class Option<T>
{
private readonly OptionType _tag;
protected Option(OptionType tag)
{
_tag = tag;
}
public OptionType Tag { get { return _tag; } }
internal bool MatchNone()
{
return Tag == OptionType.None;
}
internal bool MatchSome(out T value)
{
value = Tag == OptionType.Some ? ((Some<T>)this).Value : default(T);
return Tag == OptionType.Some;
}
public void Match(Action<T> onSome, Action onNone)
{
if (Tag == OptionType.Some)
onSome(((Some<T>)this).Value);
else
onNone();
}
public Choice<T, T2> ToChoice<T2>(T2 value)
{
if (Tag == OptionType.Some)
{
T some;
MatchSome(out some);
return Choice.NewChoice1Of2<T, T2>(some);
}
else
return Choice.NewChoice2Of2<T, T2>(value);
}
}
internal class None<T> : Option<T>
{
public None() : base(OptionType.None) { }
}
internal class Some<T> : Option<T>
{
public Some(T value)
: base(OptionType.Some)
{
_value = value;
}
private readonly T _value;
public T Value { get { return _value; } }
}
public static class Option
{
public static Option<T> None<T>()
{
return new None<T>();
}
public static Option<T> Some<T>(T value)
{
return new Some<T>(value);
}
}
public static class OptionExtensions
{
public static Option<TResult> Map<T, TResult>(this Option<T> source, Func<T, TResult> selector)
{
T value;
return source.MatchSome(out value) ? Option.Some(selector(value)) : Option.None<TResult>();
}
public static Option<TResult> Bind<T, TResult>(this Option<T> source, Func<T, Option<TResult>> selector)
{
T value;
return source.MatchSome(out value) ? selector(value) : Option.None<TResult>();
}
public static Option<TResult> Select<T, TResult>(this Option<T> source, Func<T, TResult> selector)
{
return source.Map(selector);
}
public static Option<TResult> SelectMany<TSource, TValue, TResult>(this Option<TSource> source, Func<TSource, Option<TValue>> valueSelector, Func<TSource, TValue, TResult> resultSelector)
{
return source.Bind(s => valueSelector(s).Map(v => resultSelector(s, v)));
}
}
And here is the Choice Type Implementation:
public enum ChoiceType { Choice1Of2, Choice2Of2 };
public abstract class Choice<T1, T2>
{
private readonly ChoiceType _tag;
protected Choice(ChoiceType tag)
{
_tag = tag;
}
public ChoiceType Tag { get { return _tag; } }
internal bool MatchChoice1Of2(out T1 value)
{
value = Tag == ChoiceType.Choice1Of2 ? ((Choice1Of2<T1, T2>)this).Value : default(T1);
return Tag == ChoiceType.Choice1Of2;
}
internal bool MatchChoice2Of2(out T2 value)
{
value = Tag == ChoiceType.Choice2Of2 ? ((Choice2Of2<T1, T2>)this).Value : default(T2);
return Tag == ChoiceType.Choice2Of2;
}
public void Match(Action<T1> onChoice1Of2, Action<T2> onChoice2Of2)
{
if (Tag == ChoiceType.Choice1Of2)
onChoice1Of2(((Choice1Of2<T1, T2>)this).Value);
else
onChoice2Of2(((Choice2Of2<T1, T2>)this).Value);
}
}
internal class Choice1Of2<T1, T2> : Choice<T1, T2>
{
public Choice1Of2(T1 value)
: base(ChoiceType.Choice1Of2)
{
_value = value;
}
private readonly T1 _value;
public T1 Value { get { return _value; } }
}
internal class Choice2Of2<T1, T2> : Choice<T1, T2>
{
public Choice2Of2(T2 value)
: base(ChoiceType.Choice2Of2)
{
_value = value;
}
private readonly T2 _value;
public T2 Value { get { return _value; } }
}
public static class Choice
{
public static Choice<T1, T2> NewChoice1Of2<T1, T2>(T1 value)
{
return new Choice1Of2<T1, T2>(value);
}
public static Choice<T1, T2> NewChoice2Of2<T1, T2>(T2 value)
{
return new Choice2Of2<T1, T2>(value);
}
}
EDIT:
It actually works with the Extensions below. What I don't really like about it is that this implementation adds a context specific behaviour to the Choice type. This is because the Choice1Of2 is the prefered choice because all the extension methods mainly operate on it rather than on Choice2Of2 or both. (But that's what the consuming code actually implies, so I guess it is the only way to get it working.)
public static Choice<TResult, T2> Map<T1, T2, TResult>(this Choice<T1, T2> source, Func<T1, TResult> selector)
{
T1 value1;
if(source.MatchChoice1Of2(out value1))
{
return Choice.NewChoice1Of2<TResult, T2>(selector(value1));
}
T2 value2;
if (source.MatchChoice2Of2(out value2))
{
return Choice.NewChoice2Of2<TResult, T2>(value2);
}
throw new InvalidOperationException("source (:Choice) has no value.");
}
public static Choice<TResult, T2> Bind<T1, T2, TResult>(this Choice<T1, T2> source, Func<T1, Choice<TResult, T2>> selector)
{
T1 value1;
if (source.MatchChoice1Of2(out value1))
{
return selector(value1);
}
T2 value2;
if (source.MatchChoice2Of2(out value2))
{
return Choice.NewChoice2Of2<TResult, T2>(value2);
}
throw new InvalidOperationException("source (:Choice) has no value.");
}
public static Choice<TResult, T2> Select<T1, T2, TResult>(this Choice<T1, T2> source, Func<T1, TResult> selector)
{
return source.Map(selector);
}
public static Choice<TResult, T2> SelectMany<TSource, TValue, T2, TResult>(this Choice<TSource, T2> source, Func<TSource, Choice<TValue, T2>> valueSelector, Func<TSource, TValue, TResult> resultSelector)
{
return source.Bind(s => valueSelector(s).Map(v => resultSelector(s, v)));
}
Since Choice has two type parameters, you need to fix the first one to be able to write Select and SelectMany (bind):
public abstract class Choice<T1, T2>
{
public abstract Choice<T1, T3> Select<T3>(Func<T2, T3> f);
public abstract Choice<T1, T3> SelectMany<T3>(Func<T2, Choice<T1, T3>> f);
}
their implementation is straightforward for Choice1Of2:
public override Choice<T1, T3> Select<T3>(Func<T2, T3> f)
{
return new Choice1Of2<T1, T3>(this._value);
}
public override Choice<T1, T3> SelectMany<T3>(Func<T2, Choice<T1, T3>> f)
{
return new Choice1Of2<T1, T3>(this._value);
}
and for Choice2Of2 you just need to provide the inner value to the given function:
public override Choice<T1, T3> Select<T3>(Func<T2, T3> f)
{
return new Choice2Of2<T1, T3>(f(this.Value));
}
public override Choice<T1, T3> SelectMany<T3>(Func<T2, Choice<T1, T3>> f)
{
return f(this._value);
}
You may also want a BiSelect function for mapping over both type parameters:
public abstract BiSelect<T3, T4>(Func<T1, T3> ff, Func<T2, T4> fs);
If you want to use SelectMany with the linq query syntax, you need to implement another overload which looks like:
public abstract Choice<T1, T4> SelectMany<T3, T4>(Func<T2, Choice<T1, T3>> f, Func<T2, T3, T4> selector);
The implementation for Choice1Of2 is similar to before:
public override Choice<T1, T4> SelectMany<T3, T4>(Func<T2, Choice<T1, T3>> f, Func<T2, T3, T4> selector)
{
return new Choice1Of2<T1, T4>(this._value);
}
The implementation for Choice2Of2 is then:
public override Choice<T1, T4> SelectMany<T3, T4>(Func<T2, Choice<T1, T3>> f, Func<T2, T3, T4> selector)
{
T2 val = this._value;
var e = f(val);
return e.Select(v => selector(val, v));
}
and you can do:
var choice = from x in new Choice2Of2<string, int>(1)
from y in new Choice2Of2<string, int>(4)
select x + y;
Here is one new extensions class to make 'Match' method works on IEnumerable
public static class ChoiceExtensions
{
// You need this method, because code 'select result' is a LINQ expression and it returns IEnumerable
public static void Match<T1, T2>(this IEnumerable<Choice<T1, T2>> seq, Action<T1> onChoice1Of2, Action<T2> onChoice2Of2)
{
foreach (var choice in seq)
{
choice.Match(onChoice1Of2, onChoice2Of2);
}
}
// This method will help with the complex matching
public static Choice<T1, T2> Flat<T1, T2>(this Choice<Choice<T1, T2>, T2> choice)
{
Choice<T1, T2> result = null;
choice.Match(
t1 => result = t1,
t2 => result = new Choice2Of2<T1, T2>(t2));
return result;
}
}
Also, I've changed your Choice class:
// Implement IEnumerable to deal with LINQ
public abstract class Choice<T1, T2> : IEnumerable<Choice<T1, T2>>
{
IEnumerator<Choice<T1, T2>> IEnumerable<Choice<T1, T2>>.GetEnumerator()
{
yield return this;
}
public IEnumerator GetEnumerator()
{
yield return this;
}
// These two methods work with your Devide function
// I think, it is good to throw an exception here, if c is not a choice of 1
public static implicit operator T1(Choice<T1, T2> c)
{
T1 val;
c.MatchChoice1Of2(out val);
return val;
}
// And you can add exception here too
public static implicit operator T2(Choice<T1, T2> c)
{
T2 val;
c.MatchChoice2Of2(out val);
return val;
}
// Your Match method returns void, it is not good in functional programming,
// because, whole purpose of the method returning void is the change state,
// and in FP state is immutable
// That's why I've created PureMatch method for you
public Choice<T1Out, T2Out> PureMatch<T1Out, T2Out>(Func<T1, T1Out> onChoice1Of2, Func<T2, T2Out> onChoice2Of2)
{
Choice<T1Out, T2Out> result = null;
Match(
t1 => result = new Choice1Of2<T1Out, T2Out>(onChoice1Of2(t1)),
t2 => result = new Choice2Of2<T1Out, T2Out>(onChoice2Of2(t2)));
return result;
}
// Continue Choice class
}
Your sample is slightly incorrect, because when you write:
from f1 in ReadDouble().ToChoice("Could not parse input to a double.")
from f2 in ReadDouble().ToChoice("Could not parse input to a double.")
from result in Devide(f1, f2).ToChoice("Cannot devide by zero.")
select result
in the last line you actually ignore f1 and f2. So it is impossible to see parsing error. Better write:
(
from f1 in ReadDouble().ToChoice("Could not parse input to a double.")
from f2 in ReadDouble().ToChoice("Could not parse input to a double.")
from result in
f1.PureMatch(
f1value => f2.PureMatch(
f2value => Devide(f1, f2).ToChoice("Cannot devide by zero."),
f2err => f2err).Flat(),
f1err => f1err
).Flat()
select result
)
.Match(
x => Console.WriteLine("Result = {0}", x),
x => Console.WriteLine("Error: {0}", x));
You can create nice helper methods to deal with this complicated stuff, something like PureMatch method but with more arguments

Func<> with unknown number of parameters

Consider the following pseudo code:
TResult Foo<TResult>(Func<T1, T2,...,Tn, TResult> f, params object[] args)
{
TResult result = f(args);
return result;
}
The function accepts Func<> with unknown number of generic parameters and a list of the corresponding arguments. Is it possible to write it in C#? How to define and call Foo? How do I pass args to f?
You can use Delegate with DynamicInvoke.
With that, you don't need to handle with object[] in f.
TResult Foo<TResult>(Delegate f, params object[] args)
{
var result = f.DynamicInvoke(args);
return (TResult)Convert.ChangeType(result, typeof(TResult));
}
Usage:
Func<string, int, bool, bool> f = (name, age, active) =>
{
if (name == "Jon" && age == 40 && active)
{
return true;
}
return false;
};
Foo<bool>(f,"Jon", 40, true);
I created a fiddle showing some examples: https://dotnetfiddle.net/LdmOqo
Note:
If you want to use a method group, you need to use an explict casting to Func:
public static bool Method(string name, int age)
{
...
}
var method = (Func<string, int, bool>)Method;
Foo<bool>(method, "Jon", 40);
Fiddle: https://dotnetfiddle.net/3ZPLsY
That's not possible. At best, you could have a delegate that also takes a variable number of arguments, and then have the delegate parse the arguments
TResult Foo<TResult>(Func<object[], TResult> f, params object[] args)
{
TResult result = f(args);
return result;
}
Foo<int>(args =>
{
var name = args[0] as string;
var age = (int) args[1];
//...
return age;
}, arg1, arg2, arg3);
This could become easy with lambda expressions:
TResult Foo<TResult>(Func<TResult> f)
{
return f();
}
Then usage could be like:
var result = Foo<int>(() => method(arg1, arg2, arg3));
Where method can be arbitrary method returning int.
This way you can pass any number of any erguments directly through lambda.
To support asynchoronous code we can define:
Task<TResult> Foo<TResult>(Func<Task<TResult>> f)
{
return f();
}
// or with cancellation token
Task<TResult> Foo<TResult>(Func<CancellationToken, Task<TResult>> f, CancellationToken cancellationToken)
{
return f(cancellationToken);
}
and use it like:
var asyncResult = await Foo(async () => await asyncMethod(arg1, arg2, arg3));
// With cancellation token
var asyncResult = await Foo(
async (ct) => await asyncMethod(arg1, arg2, arg3, ct),
cancellationToken);
You could try something similar to what I posted here: https://stackoverflow.com/a/47556051/4681344
It will allow for any number of arguments, and enforces their types.
public delegate T ParamsAction<T>(params object[] args);
TResult Foo<TResult>(ParamsAction<TResult> f)
{
TResult result = f();
return result;
}
to call it, simply......
Foo(args => MethodToCallback("Bar", 123));
In some cases you may be able to get away with a trick like this:
public static class MyClass
{
private static T CommonWorkMethod<T>(Func<T> wishMultipleArgsFunc)
{
// ... do common preparation
T returnValue = wishMultipleArgsFunc();
// ... do common cleanup
return returnValue;
}
public static int DoCommonWorkNoParams() => CommonWorkMethod<int>(ProduceIntWithNoParams);
public static long DoCommonWorkWithLong(long p1) => CommonWorkMethod<long>(() => ProcessOneLong(p1));
public static string DoCommonWorkWith2Params(int p1, long p2) => CommonWorkMethod<string>(() => ConvertToCollatedString(p1, p2));
private static int ProduceIntWithNoParams() { return 5; }
}
Although it is not really what asked, a simple workaround would be to define several Foo method with different number of type arguments.
It is uncommon to have function with more than 6 parameters, so one could define the following method and get away with almost every use case, while staying type safe. Renan's solution could then be used for the remaining cases.
public TResult Foo<TResult> (Func<TResult> f)
{
return f();
}
public TResult Foo<T1, TResult>(Func<T1, TResult> f, T1 t1)
{
return f(t1);
}
public TResult Foo<T1, T2, TResult>(Func<T1, T2, TResult> f, T1 t1, T2 t2)
{
return f(t1, t2);
}
...

Calling Method (with any parameter) from parameter

I am trying to write a game with OpenTK.
I want to check the error everytime I call something from GL class.
so, let say, I have this class:
public static class GLCheck
{
public static void Call(function f)
{
// Call f function
CheckError();
}
public static void CheckError()
{
ErrorCode errorCode = GL.GetError();
if (errorCode != ErrorCode.NoError)
Console.WriteLine("Error!");
}
}
so I can call function like this:
GLCheck.Call(GL.ClearColor(Color.White));
GLCheck.Call(GL.MatrixMode(MatrixMode.Modelview));
GLCheck.Call(GL.PushMatrix());
how can I do this?
thanks
----------------- Answer: -----------------
thanks for the answer!
I just realize all answers are using Delegate (Action or Func<>)
On .NET 2.0, this is not available, so you must create your own, here my GLCheck Class:
public static class GLCheck
{
public delegate void Action();
public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public static void Call(Action callback)
{
callback();
CheckError();
}
public static void Call<T>(Action<T> func, T parameter)
{
func(parameter);
CheckError();
}
}
Once again, thanks for the answer!
It won't be quite as tidy, but you can do this pretty easily with Lambda functions:
GLCheck.Call(() => GL.ClearColor(Color.White));
GLCheck.Call(() => GL.MatrixMode(MatrixMode.Modelview));
GLCheck.Call(() => GL.PushMatrix());
And Call would be defined like this:
public static void Call(Action a)
{
a();
CheckError();
}
In the case of methods GL methods without parameters, you can pass them in a bit more cleanly:
GLCheck.Call(GL.PushMatrix);
(note that there are no () after PushMatrix.)
You can use generics to create something like this:
private void Call<T> (Action<T> func, T parameter)
{
func(parameter);
CheckError();
}
where T would be a parameter. Or you can use exceptions as suggested.
Maybe you should just write your own API on top of the GL, thus resulting in much cleaner code. ie
public class MyGL
{
private TypeHere GL = new TypeHere();
public void ClearColor(Color color)
{
GL.ClearColor(color);
CheckError();
}
private void CheckError()
{
ErrorCode errorCode = GL.GetError();
if (errorCode != ErrorCode.NoError)
Console.WriteLine("Error!");
}
}
And thus you can call it with much more clear and readable code
MyGL.ClearColor(Color.White);

is it possible to convert Func<T1,T2,TResult> to Func<T2,T1,TResult>

First, foo is a Func<T1,T2,TResult> object.
Is is possible do something like
Func<T2,T1,TResult> bar = ConvertFunction(foo);
thus convert Func<T1,T2,TResult> to Func<T2,T1,TResult>.
Yes, that's possible:
Func<T2, T1, TResult> bar = (t2, t1) => foo(t1, t2);
That basically creates another delegate with switched parameters that internally simply calls the original delegate.
This is the only way to perform this kind of "conversion" if you only have a Func<T1, T2, TResult> and not a Expression<Func<T1, T2, TResult>>.
Here's the function:
class MyFuncConverter<T1, T2, TResult>
{
static Func<T1, T2, TResult> _foo;
public static Func<T2, T1, TResult> ConvertFunction(Func<T1, T2, TResult> foo)
{
_foo = foo;
return new Func<T2, T1, TResult>(MyFunc);
}
private static TResult MyFunc(T2 arg2, T1 arg1)
{
return _foo(arg1, arg2);
}
}
Sample usage:
static void Main(string[] args)
{
var arg1 = 10;
var arg2 = "abc";
// create a Func with parameters in reversed order
Func<string, int, string> testStringInt =
MyFuncConverter<int, string, string>.ConvertFunction(TestIntString);
var result1 = TestIntString(arg1, arg2);
var result2 = testStringInt(arg2, arg1);
// testing results
Console.WriteLine(result1 == result2);
}
/// <summary>
/// Sample method
/// </summary>
private static string TestIntString(int arg1, string arg2)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII
.GetBytes(arg2.ToString() + arg1);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}

Pass a method with N params as parameter in C#

I have several methods all returning void with different signature (parameters) and different names. I need to pass those methods as a parameter in a generic method that will invoke it latter. Also that need to be as transparent as possible.
Following what I got so far:
private void button1_Click(object sender, EventArgs e)
{
Action<string,int> TestHandler = Test;
InvokeMyMethod(TestHandler);
Action<string, int,object > TestHandlerN = TestN;
InvokeMyMethod(TestHandlerN);
}
public void InvokeMyMethod(Delegate Method)
{
object[] args = new object[X];
Method.DynamicInvoke();
}
public void Test(string t1, int t2)
{
MessageBox.Show(t1 + t2);
}
public void TestN(string t1, int t2, object t3)
{
MessageBox.Show(t1 + t2);
}
That is what I need:
private void button1_Click(object sender, EventArgs e)
{
InvokeMyMethod(Test);
InvokeMyMethod(TestN);
}
public void InvokeMyMethod(XXX_Type Method)
{
object[] args = new object[X];
Method.DynamicInvoke(args);
}
public void Test(string t1, int t2)
{
MessageBox.Show(t1 + t2);
}
public void TestN(string t1, int t2, object t3)
{
MessageBox.Show(t1 + t2);
}
This doesn't answer your question directly, but here is how I solve a similar problem:
public static partial class Lambda
{
public static Action Pin<T0>
(
this Action<T0> action,
T0 arg0
)
{
return () => action(arg0);
}
public static Func<TResult> Pin<T0, TResult>
(
this Func<T0, TResult> func,
T0 arg0
)
{
return () => func(arg0);
}
public static Action Pin<T0, T1>
(
this Action<T0, T1> action,
T0 arg0,
T1 arg1
)
{
return () => action(arg0, arg1);
}
public static Func<TResult> Pin<T0, T1, TResult>
(
this Func<T0, T1, TResult> func,
T0 arg0,
T1 arg1
)
{
return () => func(arg0, arg1);
}
// More signatures omitted for brevity...
// I would love it if C# supported variadic template parameters :-)
}
The idea is that if you have an Action which requires arguments, you can say:
Action<int, string> foo;
Action a = foo.Pin(5, "bleh");
Have the code generator.
Likewise, you might want to have a way to curry to some other delegate type (like Action<string, int>). The difference between my method and yours is that mine is not late-bound, but you do not appear to be using late-binding anyway, so early-binding gives you some compile-time type safety.
I'm not sure you can do what I think you are asking. You call method.DynamicInvoke with some object[], but how did you get values for those parameters?
And to answer the question before anybody asks it, I created the Lambda.Pin functions because I was tired of making this mistake:
Action<int> foo;
foreach (int i in someList)
AddAction(() => foo(i));
public void InvokeMyMethod(Delegate method) {
Method.DynamicInvoke(new object[] {"Test", 1});
}
But you need to invoke it like
InvokeMyMethod((Action<string, int>)Test);

Categories