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 casting 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.
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