Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable<T> for generic method in c#?

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?

like image 300
BlueChippy Avatar asked Dec 20 '10 10:12

BlueChippy


1 Answers

public static XElement AddOptionalElement<T>(
    this XElement parentElement, string childname, T? childValue)
    where T : struct
{
    // ...
}
like image 162
LukeH Avatar answered Sep 29 '22 12:09

LukeH