Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating nullable class

Tags:

c#

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.

like image 295
iefpw Avatar asked Mar 07 '12 21:03

iefpw


People also ask

How do you make a class nullable?

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.

Can a class be nullable?

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.

How do you make an object nullable?

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.

What is nullable in C#?

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.


4 Answers

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

like image 174
pfries Avatar answered Oct 18 '22 04:10

pfries


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.

like image 42
Ry- Avatar answered Oct 18 '22 05:10

Ry-


Just remove the questionmark. All classes are nullable by default. Only value-type objects (like struct) need to be explicitly made nullable.

like image 4
Mattias Åslund Avatar answered Oct 18 '22 06:10

Mattias Åslund


All classes are nullable. nullable is for Value types that can't be null

like image 1
Rune FS Avatar answered Oct 18 '22 06:10

Rune FS