How to make Object property of a C# class optional?

tripti sinha picture tripti sinha · Dec 13, 2019 · Viewed 7.6k times · Source

I am trying to make a model class in C# in which i require object/List properties as optional property:

public class Customer
{
        [JsonProperty("Custid")]
        public string CustId { get; set; }
        [JsonProperty("CustName")]
        public string CustName { get; set; }
}
public class Store
{
        [JsonProperty("id")]
        public string Id { get; set; }
        [JsonProperty("Name")]
        public string? Name { get; set; }
        [JsonProperty("Customer")]
        public List<Customer>? Customers{ get; set; }            *//Error 1*
        [JsonProperty("OtherProperty")]
        public object? OtherProperty{ get; set; }                *//Error 2*
}

The above code is giving error as :-
Error 1: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'
Error 2: The type 'List' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

Please Explain me the above scenario and provide me with the alternate solution.

Answer

Luaan picture Luaan · Dec 13, 2019

string, List and object are all reference types. Those are nullable by default. The Nullable type (e.g. int? is a shorthand for Nullable<int>) is only used for value types.

In C# 8.0, a new feature was introduced that allows for non-nullable reference types - i.e. reference types that explicitly disallow null assignment. This is an opt-in feature - you can enable it to allow you to more clearly show intent about the references. If you use this, the syntax used to define nullable reference types is the same as for nullable value types:

string nonNullableString = null; // Error
string? nullableString = null;   // Ok

Keep in mind that enabling non-nullable reference types means that all of the reference types that aren't followed by ? will be non-nullable; this might require you to make lots of changes in your application.

So there's your two choices. Either enable non-nullable reference types, and then you need to explicitly mark types that you want to have nullable, or stick with nullable reference types, and just use string instead of string? for the same result. I would encourage the use of non-nullable types by default, since it holds some promise for avoiding an entire class of very common programming mistakes.