Search code examples
c#user-input

How to create objects from user input - C#


I'm a beginner in OOP and have recently started coding in C#. (working in Visual Studio 2017 Console application.) After searching around for tutorials i will try my luck here.

I'm trying to make a simple program that would allow a user to make a new object book(or multiple) by asking them for input. I know how to manually create an object of the class but not how to do the same with user input. this is the code i have so far:

public class book
{
    //variables
    private string title;
    private string author;
    private string genre;
    private string series;

    //constructor
    public book(string _titel, string _author, string _genre, string _series)
    {
        this.titel = _titel;
        this.author = _author;
        this.genre = _genre;
        this.series = _series;
    }

    //method to ask user for input to create book
    public void createBook()
    {

    }

Solution

  • Console.WriteLine("Input Title: ");
    var title = Console.ReadLine();
    Console.WriteLine("Input Author: "):
    var author = Console.ReadLine();
    etc..
    var book = new Book(title,author etc...)
    

    You get the inputs as variable and then construct your object from those variables.