Reputation: 4480
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 ?
Upvotes: 1
Views: 147
Reputation: 35905
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.
Upvotes: 0
Reputation: 5744
You can't. Structs are value objects in C#. If you require them to be nullable, you need to use the syntax EMPLOYEE?
Upvotes: 2
Reputation: 249
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
Upvotes: 1
Reputation: 11471
Struct is value type - not reference type. All value types cannot be assigned to null.
Upvotes: 1