1

How to Make Structure as Null in C# ?

EMPLOYEE? objEmployee = null; EMPLOYEE stEmployee = objEmployee.GetValueOrDefault(); 

but this make stEmployee fields as null,but i want to make this structure as null. It shows stEmployee.FirstName = null,stEmployee.LastName = null

But i want to make stEmployee as null. How to achieve that ?

1
  • 3
    Use a class (recommended) or replace all instances of EMPLOYEE with EMPLOYEE?. Also as a side note, EMPLOYEE doesn't follow C# style rules and should be Employee instead. Commented Feb 6, 2012 at 7:14

4 Answers 4

2

You can't. Structs are value objects in C#. If you require them to be nullable, you need to use the syntax EMPLOYEE?

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

Comments

1

Struct is value type - not reference type. All value types cannot be assigned to null.

"Value Types" article on MSDN

4 Comments

It's possible by wrapping the value type in a Nullable<EMPLOYEE> class. C# provides some nice syntax for this too - EMPLOYEE?
Thanks, I know this, but Nullable<EMPLOYEE> is not a struct anymore :) With the same result he can create new class with property of type EMPLOYEE and assign null to and instance of that class.
@RobertRouhani and Pavel: Nullable<T> is a struct, not a class.
@phoog oh, you're right, just read article about nullable struct - that was interesting :) thank you!
1

A struct can't be null in the same way that an int can't be null, and a float can't be null - they're all value types! But in the same way that you can make a nullable type in C# you can face to struct:

When you want to have an integer type with ability of accepting null values you should follow below code:

int? x = null; 

and then you can check it as below, and also you have access to its value through x.Value

if ( x != null) { //then do blah-blah with x.Value Console.Write(x.Value * 2); } 

Now you can do the same thing with struct...

struct Book { public string title; ... } ... Book book0 = null; //It doesn't work Book? book1 = null; //It works 

Comments

0

You would need to use Nullable<T> type, which is available from .NET2.

The reason is because reference types value can be set to zeros, which would indicate that the reference type does not point to anything, it is then NULL. With the value type, you cannot simply say that it's value is all zeros, for example all zeros for an Int32 would mean just 0 value.

The main difference is for value types you directly assign value, for reference type you only assign a "memory pointer" to the value. Nullable can only be used with value types and it uses extra bit to store information whether the type is null (HasValue) or not.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.