How do I create a nullable (?
) class in C#? Like:
public class Hello1 {
public int Property1 { get; set; }
}
public class Hello2 {
Public Hello1? Property2 { get; set; } //Hello1 should work when it has "?"
}
I want to make Hello1
class to be able to take the form Hello1?
if needed.
To add a nullable type by using the Code EditorSelect the project node in Solution Explorer, and, on the Project menu, click Add Class. In the . cs or . vb file for the new class, add one or more nullable types in the new class to the class declaration.
Remarks. A type is said to be nullable if it can be assigned a value or can be assigned null , which means the type has no value whatsoever. By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.
You don't need to create a nullable type for reference types. They're already nullable. You only need to do this for Value types like int, bool, decimal, etc...
You don't need to; reference types can already be null
. As for structures, simply appending a ?
will work. So just remove the ?
, and check for null
using == null
, as usual.
Just remove the questionmark. All classes are nullable by default. Only value-type objects (like struct) need to be explicitly made nullable.
All classes are nullable. nullable is for Value types that can't be null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With