Coding practices for C# Nullable type [closed]

本小妞迷上赌 提交于 2019-12-03 05:47:07

问题


I have never used nullable types in my C# code. Now I have decided to change my coding practice by introducing nullable types in my code.

What are the major changes in the coding practices should be made while making a transition from normal datatypes to nullable data-types in case of application programming?

What are the areas that should be taken care of?

What are the points I should always watch out for?


回答1:


Nullable<T> is useful for when you need a possible invalid state for a value type, or if the data is being retrieved from a database that may contain a null value for the column. It is very common in some old FORTRAN code I am porting to C# for invalid values to be negative or 0, but this is troublesome especially when the values are used in mathematical functions. It is far more explicit to use Nullable<T> to show that possible invalid state.

It is worth mentioning that the following is the same:

Nullable<int> myNullableInt;
int? myNullableInt;



回答2:


Don't use nullable types because they are a "cool new thing" you have discovered. Use them where they are applicable and genuinely useful.

There are overheads to using them, and if used incorrectly they will unnecessarily increase the complexity of your code.

You also have to be careful to avoid null dereferences, so they place additonal burden on programmers working with that code. (In some cases this is preferable to the cost of a workaround approach though!)




回答3:


In addition I find the following property useful:

public bool? IsHappy { get; set; }

This allows me to have a tri-state boolean value: yes, no, not answered.




回答4:


A couple of other good ideas for using nullable types:

  • Don't forget the flexibility in syntax. Nullable<int> is the same as int?
  • Check for null (var.HasValue) and cast it to base type before using it as the base type.



回答5:


They seem suitable for the starting value of some value type variables.

int? lastCodeReceived;

if (lastCodeReceived.HasValue)
{
    // At least one code has been received.
}



回答6:


I rarely use nullable types. The only place I've use them is when I'm dealing with null types in the database.



来源:https://stackoverflow.com/questions/1550909/coding-practices-for-c-sharp-nullable-type

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