Tom Gullen Tom Gullen - 1 month ago 10
C# Question

Pass function as parameter

I have a function:

private static PrivateMessage GetPM()
{
using (var db = new DBContext())
{
var q = CompiledQueries.GetPMByID(db, messageID);
if (q == null) return null;
return new PrivateMessage(q);
}
}


I wish to pass this function as a parameter:

var pm = cacheObj.SetIfNotExists(GetPM);


Where
SetIfNotExists
is defined as:

public T SetIfNotExists<T>(Func<T> getCachableObjectFunction)


What do I need to modify so that I can pass
messageID
as a parameter in
GetPM()
? EG:

private static PrivateMessage GetPM(int messageID)

Answer

Wrap and typecast your output is the easiest way.

var pm = cacheObj.SetIfNotExists(() => GetPM(1));

And change GetPM header to:

private static PrivateMessage GetPM(int messageID)
Comments