I'm trying to write a method that accepts a generic input and returns null if the input is default and an XElement otherwise.
Btw, I'm pretty green at generic methods, and apparently at google-fu.
Here's what I have so far:
public static class ConversionClass<T>
{
public static XElement newXElementOrNull<T>(string name, T val)
{
if ((T.type == "String") && (val == String.Empty))
{
return null;
}
if (val == default(T))
{
return null;
}
else
{
return new XElement(name, val);
}
}
}
For some reason, C# does not like this.
It balks on the method signature (newXElementOrNull) saying:
Type parameter 'T' has the same name as the type parameter from outer type 'AddXMLTest.Converter'
And it highlights the T in the angled brackets and the T in the parameter.
To make matters worse it doesn't like the val == default(T) part because it says Operator '==' cannot be applied to operands of type 'T' and 'T'.
What am I doing wrong?
Apparently this method is inside a class that already specifies <T>
. That means that you can omit this type parameter, methods of a generic class are automatically generic too.
I would expect T.type
to cause errors as well but it depends on the type-constraints on the outer class. To get a full answer, post the outer definition (not all members) of that class.
it doesn't like the
val == default(T)
That is most likely a follow-up error of the first.
Type parameter 'T' has the same name as the type parameter from outer type 'AddXMLTest.Converter'
So the class outside of this method (not shown) must be using <T>
as well. You won't be able to do that. Name it (on the method that is) something like <K>
.
To make matters worse it doesn't like the val == default(T) part because it says Operator '==' cannot be applied to operands of type 'T' and 'T'.
This should be resolved when you stop using <T>
and change it so something like default(K)
.
Further, I'm pretty sure that this T.type
isn't going to compile. I'm pretty sure that evaluation should be something like:
if ((val is typeof(string) && string.IsNullOrEmpty(val))
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