3

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#

2
  • @nasmifive: This won't work without adding making the variable explicitly nullable Commented Apr 4, 2011 at 17:31
  • @nasmifive: I suppose samadhi wish to have some Database-like behaviour. In databases you can have some fields being "not set" i.e. null. I can even imagine some scenarios where you can have gender not set, e.g. police have found some human remains and they don't surely now was it male of female (it's awful but it's just an example of scenario where you can have gender not set). Commented Apr 4, 2011 at 17:47

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

0

This is how you can create Nullable types in C#

Nullable<Gender>

or short:

Gender?

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.