I have this code:
//Return null if the extension doesn't have the value, returns the value if it does.
private T? getValue<T>(IEnumerable<Extension> extension, string attributeName)
{
IEnumerable<Extension> ext = extension.Where(e => e.attributeName == attributeName);
if (ext.Count() > 0)
{
return (T)ext.First().Attribute;
}
return null;
}
I’m calling it like:
//This works:
retVal.byteValue= getValueFromExtension<byte>(u, "ByteToGet") ?? 0;
//This doesn't work:
getValueFromExtension<string>(u, "Text") ?? "";
I get the compile error: “Error Message: “Cannot convert type ‘string?’ to ‘string’ “
How can I do effectively the idea in the code above without creating a new method?
I feel like I’m checking if it’s null with the ?? operator, so, if the string is null, it will always be set to an empty string. It is handled how I expect for byte and int, why not for string?
FYI, the byteValue above, is of type byte, not byte?.
It seems you want
nullif it is a reference type and0if it is a number or similar value type. You can simply use thedefaultkeyword to get such a value fromT. Also, you might want to add thethiskeyword to the first argument so that it can be used as an extension method.