user3653380
user3653380

Reputation: 17

Make a method the input parameter

I'm making a (simple) application that displays a fair bit of text to the console for the user to interact with. After each part of the method has been completed for aesthetic reasons I clear the console. As my method is basically a container of other methods this will be quite long (I've not finished it) which creates a lot of code repetition which I'd like to avoid.

My (unfinished) method:

public void RegisterTheUser()
        {
            SpecialCaseVariables s = new SpecialCaseVariables();
            Console.WriteLine(Variables.Default.registrationMsg + s.NewLine + s.NewLine);
            Console.Clear();
            string username = GetUsername();
            Console.Clear();
            string password = GetPassword();
            Console.Clear();
            string forename = GetForename();
            Console.Clear();
            string surname = GetSurname();
            Console.Clear();
            string displayAddress = GetDisplayAddress();
            Console.Clear();
            string phoneNumber = GetPhoneNumber();
            Console.Clear();
            Console.WriteLine(username + " " + password + " " + forename + " " + surname + " " + displayAddress + " " + phoneNumber);
            VerifyLogin(username, password);
            Console.ReadKey();

        }

So what I was wondering was how I could basically do something that will do something similar to the following:

private string DoMethodAndClear(method methodToDo) //the type would be method if it could work?
{
Console.Clear;
var result = methodToDo();
return result;
}

So in my RegisterTheUser method I could just have a bunch of the DoMethodAndClear methods instead of x method then clear, y method then clear.

Upvotes: 0

Views: 83

Answers (1)

Selman Genç
Selman Genç

Reputation: 101701

You could use a Func<string> delegate:

private string DoMethodAndClear(Func<string> methodToDo) 
{
    var result = methodToDo();
    Console.Clear();
    return result;
}

Then call it:

string username = DoMethodAndClear(GetUsername);
string password = DoMethodAndClear(GetPassword);
string forename = DoMethodAndClear(GetForename);
string surname = DoMethodAndClear(GetSurname);
string displayAddress = DoMethodAndClear(GetDisplayAddress);

Upvotes: 3

Related Questions