How to?

  • Thread starter Thread starter Jacek Jurkowski
  • Start date Start date
Jacek Jurkowski said:
Make a class non-nullable like DateTime is?

All classes are nullable. Classes are reference types and any variable of a
reference type can be null.

DateTime is a structure. Structs are non-nullable because they are value
types.

You can therefore make a class non-nullable by converting it a stuct:-

public struct MyThing
{
...
}

However structs do have some limitations, you cannot define a default
constuctor, you cannot inherit from a structure. When you assign a variable
or pass the structure as a parameter you should remember that a copy is
being made of the whole state not a copy of a reference to an object.
 
When declaring a type add "?" to the end.

Like so:

DateTime? dateTime = null;
ushort? myUshort = null;
 
When declaring a type add "?" to the end.

Like so:

DateTime? dateTime = null;
ushort? myUshort = null;

Thats the reverse of the question asked. The question asked is "How to make
a class non-nullable like DateTime is?" not "How to make a structure like
DateTime nullable?"
 
Back
Top