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 null if it is a reference type and 0 if it is a number or similar value type. You can simply use the default keyword to get such a value from T. Also, you might want to add the this keyword to the first argument so that it can be used as an extension method.
private T getValue<T>(this IEnumerable<Extension> extension, string attributeName)
{
Extension ext = extension.SingleOrDefault(e => e.attributeName == attributeName);
if (ext != null)
return (T)ext.Attribute;
else
return default(T);
}
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