samadhi
samadhi

Reputation: 41

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#

Upvotes: 3

Views: 651

Answers (4)

codymanix
codymanix

Reputation: 29468

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".

Upvotes: 0

TomTom
TomTom

Reputation: 62093

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.

Upvotes: 4

Paweł Smejda
Paweł Smejda

Reputation: 2005

This is how you can create Nullable types in C#

Nullable<Gender>

or short:

Gender?

Upvotes: 0

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60684

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.

Upvotes: 8

Related Questions