Home > database >  How do I use multiple methods with user inputs?
How do I use multiple methods with user inputs?

Time:10-23

I'm pretty new to C# and I have a project coming up. Recently, I've created another dummy project just to get this fact down. I'm just trying to get the user to input their name and for it to be displayed. Here's what I've got so far, which of course is not working. Some help would be greatly appreciated, even if this seems like a very dumb or basic question.

public class Employee
{
    private string firstName;

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public string GetNames()
    {
        Console.WriteLine("Please enter your first name:");
        firstName = Convert.ToString(Console.ReadKey());
        return firstName;
    }

    public Employee()
    {
        firstName = this.firstName;
    }

    public static void Display(string firstName)
    {
        Console.WriteLine(firstName);
    }

}

public class Program
{
    static void Main(string[] args)
    {
        Employee employee = new Employee();
        Console.Write(employee.FirstName);
    }
}

CodePudding user response:

I would like to take you through this step-by-step, starting with a simple implementation of the Main() body. This all may be too detailed for your needs, but hopefully it provides some helpful insights.

The steps are:

  1. Achieving the main goal, the basic way
  2. Extracting logic into methods
  3. Introducing the Employee class
  4. Embedding the methods in the Employee class

(Note that this is just a suggested collection of steps, it is by no means the only step-by-step way.)


1. Achieving the main goal, the basic way

Let's start with the main goal, which you have stated to be:

I'm just trying to get the user to input their name and for it to be displayed.

As commented in this existing answer, Console.ReadLine() should be used rather than Console.ReadKey() to read a full inputted line (which is terminated by the user pressing Enter).

Seeing as Console.ReadLine() returns a string, there is no need for conversion of the return value to a string.

Your main goal (in its simplest form) does not include any Employee class. It may be achieved by assigning the return value of Console.ReadLine() to a variable, and using that variable in the subsequent call to Console.WriteLine() to display the first name:

public static void Main()
{
    Console.WriteLine("Please enter your first name:");
    var firstName = Console.ReadLine();

    Console.WriteLine("Your first name is "   firstName);
}

When a user runs this and types Laura, the console output will be:

Please enter your first name:
> Laura
Your first name is Laura

Example fiddle here.


2. Extracting logic into methods

Now, the two first code lines in the Main() method are used to request the user for their first name:

Console.WriteLine("Please enter your first name:");
var firstName = Console.ReadLine();

Let's extract that logic into a method.

Seeing as Main() is a static method, any method called from within Main() also needs to be a static method. Hence, we make our method static and lets it return what the user inputted after we requested their first name:

public static string RequestFirstName()
{
    Console.WriteLine("Please enter your first name:");
    var firstName = Console.ReadLine();
    
    return firstName;
}

With this method in place, our Main() body can now be simplified by calling the method:

public static void Main()
{
    var firstName = RequestFirstName();

    Console.WriteLine("Your first name is "   firstName);
}

Onto the next part. The last line in Main() is used to display the name that the user just provided us with:

Console.WriteLine("Your first name is "   firstName);

If we want to extract that into a method, we will need to include an input parameter to know which name to actually display; just like you have done in your own implementation. The method does not need to return anything, as its purpose is simply to write to the console. Just like RequestFirstName(), this method also needs to be static:

public static void DisplayFirstName(string firstName)
{
    Console.WriteLine("Your first name is "   firstName);
}

Again, Main() can be simplified by calling the newly implemented method:

public static void Main()
{
    var firstName = RequestFirstName();

    DisplayFirstName(firstName);
}

Running this code, the console will still display the same as in step 1:

Please enter your first name:
> Laura
Your first name is Laura

Example fiddle with the resulting code snippets here.


3. Introducing the Employee class

I would suggest starting with a very simple implementation of the Employee class. Perhaps simply containing one property: FirstName.

But first, a side note on your current implementation of Employee:
You have implemented a property FirstName, which uses a backing field for getting and setting its value. (Any private field should (according to the name convention) be prefixed with an underscore, so I will use that in this example.)

Your implementation of Employee (when disregarding the constructor and the methods) looks like this:

public class Employee
{
    private string _firstName; // Backing field for property

    public string FirstName    // Property
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
}

When a property directly gets and sets the value of the backing field, straight-forward, like in this example, implementing an explicit backing field is not necessary. As explained in the Property syntax documentation, all you need is an auto-implemented property:

public class Employee
{
    public string FirstName { get; set; } // Auto-implemented property
}

Now, we can create an Employee instance inside Main(), and set its FirstName by using the methods we implemented in step 2:

public static void Main()
{
    var employee = new Employee();
    
    employee.FirstName = RequestFirstName();

    DisplayFirstName(employee.FirstName);
}

The console will still display the same as previously when running this code:

Please enter your first name:
> Laura
Your first name is Laura

Example fiddle with the resulting code snippets here.


4. Embedding the methods in the Employee class

Finally, it's time to sew it all together. We will embed our request and display methods in Employee, so that the methods can be called on the Employee instance (employee) that we have created in Main().

But, we cannot simply copy and paste those methods into the Employee class. Or, well, we could do it, but if we did, they would not function the way we want them to function. For instance, upon requesting a name, the provided name would not be assinged to the Employee instance's FirstName property.

So we need to make a few changes. First, let's look at the request method from step 2:

  1. We want to be able to call the request method on an Employee instance (employee). Any static method which is defined inside a class cannot be called on an instance of that class from outside the class. Hence, we need to make our methods non-static by removing the static keyword. (Read more about the difference between a class and an instance of a class here.)
  2. We want to assign the provided name to FirstName. Hence, var firstName needs to be replaced with FirstName.
  3. Seeing as FirstName will now be set inside the request method, there is no need to actually return that value. We will switch the return type from string to void and omit the return statement.

Our original request method

public static string RequestFirstName()
{
    Console.WriteLine("Please enter your first name:");
    var firstName = Console.ReadLine();
    
    return firstName;
}

can hence be embedded in Employee as follows:

public class Employee
{
    public string FirstName { get; set; }

    public void RequestFirstName()
    {
        Console.WriteLine("Please enter the employee's first name:");
        FirstName = Console.ReadLine();
    }
}

Similarily, the display method needs some adjustment before embedding it in Employee.

Just like the request method, the display method needs to be non-static. In addition, we can remove the input parameter; seeing as the name we want to display is already accessible for us in Employee. We will therefore replace firstName with the property FirstName inside the Console.WriteLine() statement.

The original display method

public static void DisplayFirstName(string firstName)
{
    Console.WriteLine("Your first name is "   firstName);
}

can hence be embedded in Employee as follows:

public class Employee
{
    public string FirstName { get; set; }

    public void DisplayFirstName()
    {
        Console.WriteLine("The employee's first name is "   FirstName);
    }
}

After embedding both methods in Employee

public class Employee
{
    public string FirstName { get; set; }
    
    public void RequestFirstName()
    {
        Console.WriteLine("Please enter the employee's first name:");
        FirstName = Console.ReadLine();
    }
    
    public void DisplayFirstName()
    {
        Console.WriteLine("The employee's first name is "   FirstName);
    }
}

, we can call both methods on our Employee instance, employee:

public static void Main()
{   
    var employee = new Employee();

    employee.RequestFirstName();
    employee.DisplayFirstName();
}

In practice, what we do is:

  1. create an instance of Employee and assign it to employee
  2. request (and assign) the first name of employee by calling the request method on the instance
  3. display the first name of employee by calling the display method on the instance

The console will display the following:

Please enter the employee's first name:
> Laura
The employee's first name is Laura

Example fiddle with the resulting code snippets here.

CodePudding user response:

Use Console.ReadLine()

Console.WriteLine("Please enter your first name:");
firstName = Console.ReadLine();

Console.ReadKey() only returns one character / key

  • Related