I have a class (used by filehelpers) which gives me an error when I try to define a nullable string:
public String? ItemNum;
The error is:
Error 1 The type 'string' must be a non-nullable value type in order
to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
This occurs even with the lowercase string
, though I haven't yet seen a difference between those.
Using another type such as int, decimal etc is fine:
public decimal? ItemNum;
Some general looking on the net talks about defining constructors by field etc, but given the other fields work fine, what's special about string? Is there an elegant way to avoid it?
string
is reference type, reference types are nullable in their nature.
When you define public string ItemNum
, it is already nullable.
Nullable
struct was added to allow make value types nullable too.
When you declare public decimal? ItemNum
, it is equivalent to public Nullable<decimal> ItemNum
.
Nullable
struct has definition:
public struct Nullable<T> where T : struct, new()
where T : struct
means that T
can be only value type.
Description in MSDN is very detailed Nullable Structure.
Quote:
For example, a reference type such as String is nullable, whereas a value type such as Int32 is not. A value type cannot be nullable because it has enough capacity to express only the values appropriate for that type; it does not have the additional capacity required to express a value of 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