开发者

Creating nullable data types in c#

I have a data type called

public enum Gender { Male, Female }

But some case i need to pass the开发者_开发知识库 vale for the gender as empty. So how can i create nullable Gender in C#


Either

Gender? myGender = null;

Or

Nullable<Gender> myGender = null;

The first variant is exactly the same as the second, but it just C# syntactic sugar to ease the readability of nullable variables.


have a data type called public enum Gender = {Male, Female}; But some case i need to pass the vale for the gender as empty

Actually medically there are more than two genders. Anyhow, besides....

Nullable<Gender>.... you dont need that.

Gender.Undefined = 0 is valid AND needed as per best practice. Atually Gender.Nothing is required per .NET enum coding guidelines.


This is how you can create Nullable types in C#

Nullable<Gender>

or short:

Gender?


If the "Unspecified" gender should be handled by your application like any other genders, then it is often useful to do it this way:

public enum Gender
{
  Unspecified,
  Male, 
  Female,
}

Note that in that case, "Unspecified" will be the default value of the enum since its value is zero/0. So when declaring an Gender variable without assigning a value to it it will be automatically "Unspecified".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜