How can I write a generic method that can take a Nullable object to use as an extension method. I want to add an XElement to a parent element, but only if the value to be used is not null.
e.g.
public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T childValue){
...
code to check if value is null
add element to parent here if not null
...
}
If I make this AddOptionalElement<T?>(...)
then I get compiler errors.
If I make this AddOptionalElement<Nullable<T>>(...)
then I get compiler errors.
Is there a way I can acheive this?
I know I can make my call to the method:
parent.AddOptionalElement<MyType?>(...)
but is this the only way?
public static XElement AddOptionalElement<T>(
this XElement parentElement, string childname, T? childValue)
where T : struct
{
// ...
}
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