Nullable 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(...) then I get compiler errors. If I make this AddOptionalElement>(...) 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?

10
задан Oded 20 December 2010 в 10:55
поделиться