문제

a rookie in Csharp have a question. If I have

string phoneNumber = Console.ReadLine();

how can I shorthand write the if/else if this is blank to add "no phone number" to that string.

Something that's like this one in php

$phoneNumber = (empty($get_phonenumber) ? "no phone number" : $get_phonenumber);
도움이 되었습니까?

해결책

Console.ReadLine() returns an empty string if nothing is entered.

var readLine = Console.ReadLine();
var phoneNumber = String.IsNullOrEmpty(readLine) ? "default" : readLine;

If you're using .NET 4 or above you can use String.IsNullOrWhiteSpace(readLine) to detect if the line only contains whitespaces too.

다른 팁

You can try:

string s;
string phone = String.IsNullOrEmpty(s=Console.ReadLine()) ? "no phone number": s;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top