开发者

Why do casting to (int?) work while (string?) doesnt in LINQ queries

I'm writing a simple LINQ to XML query. As often, the some elements might be missing for some nodes in the XML document. To solve this issue, I tried to use nullable types and the coalesce operator as proposed by Scott Guthrie. Whan effect that I noticed is that casting elements to (string?) dit not work while casting to (int?) worked just fine. An example:

var modules = from module in XMLConfig.Descendants("module")
                          select new MyApp.Modules.Manager
                          {
                              ManagerUrl = (string?)module.Element("Manager") ?? "http://localhost/default.asmx",
                              ManagerType = (int?) module.Element("ManagerType") ?? 1,
                              ManagerNumber = (int?) module.Element("ManagerNumber") ?? 1,
                              PrinterNr = (int?) module.Element("PrinterNr") ?? 1,
                              TextNr = (int?) module.Element("TextNr") ?? 100,
                              Name = module.Element("Name").Value
                      };

This gave me the compiler error:

Cannot convert type 'string?' to 'string'

However, there are no complaints when casti开发者_开发知识库ng to (int?). If anyone could explain the reason for this behaviour (?) I would really appreciate it.


A string is a reference type, i.e. it is already "nullable". There is no need to wrap it in Nullable<T> as is required for value types which cannot be null.

This works:

ManagerUrl = (string)module.Element("Manager") ?? "http://localhost/default.asmx"
  • (string)module.Element("Manager") returns null if the Manager element doesn't exist, and the contents of the element otherwise.

  • (int)module.Element("ManagerType") would throw an exception if the ManagerType element doesn't exist, because a int cannot be null (value type).

  • (int?)module.Element("ManagerType") does not throw an exception if the ManagerType element is missing, because a int? can be null (nullable type).


This is because Nullable requires that T is a valuetype. string is a reference type, and is always nullable for that reason.


String is a reference type, thus nullability is implcit. The ? modifier is for adding nullability to value types that don't already support it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜