Pass string if the parameter value is null

Using ternary it would be like:

getBookInfo (bookId == null ? "TBD" : bookId, bookName == null ? "TBD" : bookName, bookAuthor == null ? "TBD" : bookAuthor)

but I think that is not very clear to read...


Just put an if condition inside this function and check for null values of these three variables and if found null, you can assign the default values immediately after the if check and then continue further execution.

Something like this :

getBookInfo (string bookId, string bookName, string bookAuthor)
{
   bookId = (bookId == "" ) ? bookId : "TBD";
   // other variables same way.
}

Hope this clears it.


Try doing it this way when calling your method:

getBookInfo (bookId ?? "TBD", bookName ?? "TBD", bookAuthor ?? "TBD");

The ternary operator ?: is a waste when you can use the null coalescing operator ??.

Tags:

C#