C# How to write this ternary operation

GetDati(id).Tables[0].Rows.count > 0 ? GetDati(id).Tables[0].Rows[0]: null; 

How should I write this line? I want to call only one time the GetDati().

Add Comment
4 Answer(s)

i want to call only 1 time the fnuction GetDati

Then call it only once and store the result in a variable. For example:

var dati = GetDati(id); var result = dati.Tables[0].Rows.count > 0 ? dati.Tables[0].Rows[0]: null 
Answered on August 30, 2020.
Add Comment

You can also take advantage of pattern matching in C# 8:

var result = GetDati(id).Tables[0].Rows is var rows && rows.Count > 0 ? rows[0] : null; 

The is introduces a test against a pattern. A var pattern will always succeed, and assigns the result to the rows variable.


That said, I find the version used by @David to be clearer, but I know some people prefer using a var pattern.

Answered on August 30, 2020.
Add Comment
var rows = GetDati(id).Tables[0].Rows; var result = rows.count > 0 ? rows[0]: null; 
Answered on August 30, 2020.
Add Comment

Thank you but if I need to call this on constructor like this:

Public myclass(DataRoe dr):this(){    Do something }  Public myclass(id):this(getdati(id).tables[0].rows[0]){} 
Answered on August 30, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.