Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# User Input Validation

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading