Search code examples
c#classconsole

Crash when class write to console


I'm going to get another user and enter which month he wants and find the quarter.

Thought of writing the code inside a class as I need more training on how to use classes.

The program asks whose month it is and I can enter. But now when I type "January" only programs crash.

I assume that it should show which quarter "january" is in

namespace ConsoleApp1
{
internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Write a month");
        
        var mc = new MyClass();
        mc.month = Convert.ToString(Console.ReadLine());
    }
    public class MyClass
    {
        public string month;

        public string Prop
        {
            get
            {
                return month;
            }
            set
                { if (Prop == "january")
                {
                    Console.WriteLine("1.quarter");
                }
            }
        }
    }
  }
}

Solution

  • Consider presenting a menu which in the case below uses a NuGet package Spectre.Console and docs. This gives you an opportunity to work with classes and ensures, in this case input is a valid month along with reties and how to exit.

    enter image description here

    First a class for the menu.

    public class MonthItem
    {
        public int Index { get; }
        public string Name { get; }
    
        public MonthItem(int index, string name)
        {
            Index = index;
            Name = name;
        }
    
        public override string ToString() => Name;
    }
    

    Class which creates the menu

    class MenuOperations
    {
    
        public static SelectionPrompt<MonthItem> SelectionPrompt()
        {
            var menuItemList = Enumerable.Range(1, 12).Select((index) =>
                new MonthItem(index, DateTimeFormatInfo.CurrentInfo.GetMonthName(index)))
                .ToList();
    
            menuItemList.Add(new MonthItem(-1, "Exit"));
    
            SelectionPrompt<MonthItem> menu = new()
            {
                HighlightStyle = new Style(Color.Black, Color.White, Decoration.None)
            };
    
            menu.Title("[yellow]Select a month[/]");
            menu.PageSize = 14;
            menu.AddChoices(menuItemList);
    
            return menu;
    
        }
    }
    

    Present menu, get selection and show details or exit.

    static void Main(string[] args)
    {
        while (true)
        {
            Console.Clear();
    
            var menuItem = AnsiConsole.Prompt(MenuOperations.SelectionPrompt());
            if (menuItem.Index != -1)
            {
                AnsiConsole.MarkupLine($"[b]{menuItem.Name}[/] index is [b]{menuItem.Index}[/]");
                Console.ReadLine();
            }
            else
            {
                return;
            }
        }
    }