What you have done:
Search(list.Contains(item));
this will first evaluate the inner expression list.Contains(item)
, which is a boolean value, not a function with a boolean return value. Next, this value and not the function will be passed to Search()
, which is not possible and results in a compiler error.
You have two choices: use lambda expressions as noted by Guffa already:
class Program
{
static void Main(string[] args)
{
SearchTime();
}
static int Search(Func<bool> func)
{
int start = Environment.TickCount;
func();
int end = Environment.TickCount;
return end - start;
}
static void SearchTime()
{
IList<string> list = new []{"item"};
IDictionary<string, string> dictionary = new Dictionary<string, string> { { "key", "value" } };
int ticks1 = Search(() => list.Contains("item")); // Note: use () =>
int ticks2 = Search(() => dictionary.ContainsKey("key")); // Note: use () =>
/* some more code */
}
}
If you don't like the () =>
syntax, you can place code into separate methods:
class Program2
{
static void Main(string[] args)
{
SearchTime();
}
static int Search(Func<bool> func)
{
int start = Environment.TickCount;
func();
int end = Environment.TickCount;
return end - start;
}
static void SearchTime()
{
int ticks1 = Search(ListContains); // Note: do not use () on ListContains
int ticks2 = Search(DictionaryContainsKey); // Note: do not use () on DictionaryContainsKey
/* some more code */
}
static IList<string> list = new[] { "" };
static bool ListContains()
{
return list.Contains("item");
}
static IDictionary<string, string> dictionary = new Dictionary<string, string> {{"key","value"}};
static bool DictionaryContainsKey()
{
return dictionary.ContainsKey("key");
}
}