Have I completely bastardized delegates?

I like to use a separate project for testing calls against one of our API's, and to make things simpler I just use a console project. I thought I'd whip up a quick'n'dirty console menu class since I can't find anything already existing for this. I'm really new to delegates, and have found I can't use a Func delegate against a non-static method. Would someone be able to help me understand what I'm doing wrong? Thank you! * This code works, but I'd like to be able to add menu items with non-static methods. Is that a dumb thing to say?

namespace ConsoleMenu { public class MenuItems { public string Name { get; set; } public Func<bool> Func { get; set; } public MenuItems(string n, Func<bool> f) { Name = n; Func = f; } } public class ConsoleMenuClass { private List<MenuItems> items = new List<MenuItems>(); private MenuItems quitItem = new MenuItems("q", QuitMenu); public void AddMenuItem(string displayText, Func< bool > MyMethod ) { items.Add(new MenuItems(displayText, MyMethod)); } public void SetQuitMenuItem(string displayText, Func<bool> QuitMethod) { quitItem = new MenuItems(displayText,QuitMethod); } public void DisplayMenu(string menutitle, string prompt) { Console.WriteLine("\n--- {0} ---", menutitle); while (true) { foreach (MenuItems m in items) { int i = items.IndexOf(m); Console.WriteLine(i + ") " + m.Name); } Console.WriteLine("q){0}", quitItem.Name); Console.Write("\n{0}: ", prompt); string s = Console.ReadLine(); if (s == "q") { quitItem.Func(); return; } items[Convert.ToInt32(s)].Func(); } } public static bool QuitMenu() { return true; } } class Program { public static Session mySession = new Session(connectionString); private static void Main(string[] args) { ConsoleMenuClass myMenu = new ConsoleMenuClass(); myMenu.AddMenuItem("PartNum Lookup Performance", PartNumTimings); myMenu.AddMenuItem("Thing1", Thing1); myMenu.AddMenuItem("Thing2", Thing2); myMenu.SetQuitMenuItem("Quit", Quit); myMenu.DisplayMenu("Tester", "Choose"); } private static bool Thing1() { Console.WriteLine("Thing1"); return true; } private static bool Thing2() { Console.WriteLine("Thing2"); return true; } private static bool Quit() { mySession.Dispose(); return true; } static private bool PartNumTimings() { //stuff } } } 

by fievelm via /r/csharp

Leave a Reply