Checking Console.ReadLine()!=null

前端 未结 4 626
执念已碎
执念已碎 2021-01-06 22:51

I am making a CMD for my application, and figure I have a trouble when I check `Console.ReadLine != null``

string input = Console.ReadLine();
 if(input != nu         


        
相关标签:
4条回答
  • 2021-01-06 23:33

    Instead of just checking for null, try checking if it is empty or null using String.IsNullOrEmpty because, when you do not input anything and press Enter, you get an empty string which results in an

    An unhandled exception of type 'System.IndexOutOfRangeException'

    Your updated full code should be as follows

    string input = Console.ReadLine();
    if (!string.IsNullOrEmpty(input) )
    {
        SomeFunction(input);
    }
    
    0 讨论(0)
  • 2021-01-06 23:44
    if(!string.IsNullOrWhiteSpace(input))
        DoYourWork(input);
    
    0 讨论(0)
  • 2021-01-06 23:51

    Thanks Every one!

    i figured that i can just check if length of string is 0.

    if(input.Length==0) //(Actually, will check if input.Length !=0 before calling function based on original source)
    

    pretty simple. but

    !string.IsNullOrEmpty(input)
    

    works as well. every day learning something new. thanks for your help!

    0 讨论(0)
  • 2021-01-06 23:52

    When you hit ENTER, Console.ReadLine returns empty string. It doesn't return null. Use string.IsNullOrEmpty to check instead.

    if(!string.IsNullOrEmpty(input))
    

    According to documentation it will return null only if you press CTRL + Z.

    0 讨论(0)
提交回复
热议问题