質問

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