Reputation: 149
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.
Upvotes: 4
Views: 44273
Reputation: 63732
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.
Upvotes: 11
Reputation: 5203
If you aren't using C# 8
:
object?
doesn't exists. object
is already nullable.
List<Customer>?
doesn't exists. List<Customer>
is already nullable.
If you want to use nullable reference types
you must update your compiler version!
Upvotes: 2
Reputation: 1137
The Nullable<T>
type requires that T is a non-nullable value type, for example int
or DateTime
. Reference types like string
or List
can already be null. There would be no point in allowing things like Nullable<List<T>>
so it is disallowed.
Upvotes: 0