Is “If” condition better than ?? and casting

╄→гoц情女王★ 提交于 2019-12-05 01:52:23

I always use null-coalescing operator in such cases:

command.Parameters.AddWithValue("@name", value ?? DBNull.Value);

command.ExecuteScalar() as int? ?? -1;

etc.

It increases code readability, decreases branching depth. Also was created especially for database-related scenarios such as ADO.NET.

The null coalescing operator (??) is a better approach because it does the same thing as your initial block but in a single, easy to read line. This makes the code more readable and more maintainable.

This is one of many examples of syntactic sugar, that is to say code statements which are "shortcuts" for representing a commonly-used idea.i++ is another example of this, as it replaces i = i + 1. It is cleaner and simpler, just like ??.

In your example, approach 2 is better. You should not repeat yourself, and apprach 1 has the code and the parameter name twice. If you want to change the paramater name, you should do so on two places, and this is a hassle.

The real code to compare this to is this:

object value = DBNull.Value;
if (reportID2 != null)
{
    value = reportID2;
}
command.Parameters.AddWithValue("@report_type_code", value);

If you use this or the ?? operator is a matter of personal preference. I think the if is more clear, especially because you need parenthesis and casting in the case of the coalesce operator.

I'd prefer the ?? operator. Although brevity does not always lead to better readability, in this case it does because as a reader you don't have to compare what is equal and what is different between the two lines of the if and else. Furthermore, you eliminated duplication of code (which is always good!). Consider the case you rename your database field name @report_type_code. Then you only have to alter it at one place.

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