C# User Input Validation

157 views Asked by At

how can I validate user input in my method with my interface, where all allowed inputs are stored? if I do so then I get System.NullReferenceException:

public interface INumbUnit
    {
        public string UnitName { get; set; }


    }

public void ValidateNumb()
        {
            INumbUnit? x = null;

            while (string.IsNullOrEmpty(UserSourceUnit))
            {
                Console.WriteLine("[ERROR] Input can't be empty! Please try again.");
                ChooseUnits();
            }

            while(UserSourceUnit != x.UnitName) //0Reference
            {
                Console.WriteLine("[ERROR] No such unit for selection! Please try again.");
            }

        }

UserSourceUnit is just a Console.ReadLine

UnitNames are stored in extern classes but there is still a reference to them, so I don't think that's the problem

1

There are 1 answers

0
Thomas Koelle On BEST ANSWER

I suspect you are new to programming, so you have to imagine that both INumbUnit and UnitName can be null.

So either you want to do a check for INumbUnit beeing null, or you want to make sure it is never null.

And you need to understand that this line

INumbUnit? x = null;

most likely need to be replaced with a real object, like

INumbUnit? x = new NumbUnit();

And then you do another class

public class NumbUnit:INumbUnit