1

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

askldq
  • 13
  • 3
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Klaus Gütter Feb 09 '23 at 14:25

1 Answers1

1

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
Thomas Koelle
  • 3,416
  • 2
  • 23
  • 44