Checking Console.ReadLine()!=null

偶尔善良 提交于 2019-12-20 04:26:19

问题


i am making a CMD for my applcation, and figure i have a trouble when i check Console.ReadLine!=null

---Full Code---

   string input = Console.ReadLine();
    if(input!=null)
    {
    SomeFunction(input);
    }

---End Of Code---

in SomeFunction() i split this string, so for example:

  Console.WriteLine(input[0]);

so Problem is:

It works if user hits enter once. But if use does that again i am getting an exception: That [0] does not exist.


回答1:


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.




回答2:


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!




回答3:


if(!string.IsNullOrWhiteSpace(input))
    DoYourWork(input);



回答4:


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);
}


来源:https://stackoverflow.com/questions/26338571/checking-console-readline-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!