开发者

Class in c# (with filehelpers) - nullable strings giving an error when other nullable types aren't

I have a class (used by filehelpers) which gives me an error when I try to define a nullable string:

public String开发者_StackOverflow社区? 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜