generics problem

G

Guest

I need to write a method that does something like the following. In general
it returns a nullable of the same type as the one passed in. Here is the
problem. If I try to assign a value to the nullable by uncommenting the line
' //tRet = -999;' it won't compile (cannot implicity convert type xxx to T?)
.. Is there a way I can do what I want...perhaps with some reflection method?
If I am heading down the wrong direction with this pleae let me know.

using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// should have the (3,3) record in the database at this point...
int? i1 = 10;
int? i1r = (int?)MyMethod(i1);
int? i2 = null;
int? i2r = (int?)MyMethod(i2);
float? f1 = 10f;
float? f1r = (float?)MyMethod(f1);
float? f2 = null;
float? f2r = (float?)MyMethod(f2);
}
private static T? MyMethod<T>(T? myVal) where T : struct
{
try
{
if (myVal.HasValue)
return myVal;

// Now make the constructed type.
Type cType = typeof(Nullable<>).MakeGenericType(typeof(T));
T? tRet = (T?)Activator.CreateInstance(cType);
//tRet = -999;

return tRet;
}
catch
{
return null;
}
}
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Brian,

It's not going to work, because 999 is a numeric value, and T can be any
kind of structure (like a DateTime, a TimeSpan) which you can't assign that
value to.

You would have to change your method to take 999 as input, and then
assign it in the method to the parameter passed in:

private static T? MyMethod<T>(T? myVal, T value) where T : struct
 
S

ssamuel

Brian,

I think you may be going about things the wrong way. It appears as if
you're using some very strong tools (generics, reflection, etc.) for
something that may just as easily be solved with something like a
typed DataSet. The problem of typing common database types (int,
float, etc.) is well-solved.

It looks like the reason you're having this problem is that you're
making assumptions about the type passed to your method. It looks like
you expect that the only thing to be passed is some numerical type,
hence your attempt to return -999. The compiler won't allow this
because you could be given a non-numeric struct. Consider these
structs:

public struct Complex { public int real; public int imaginary; }

public struct WebListItem { public string name; public string value; }

While either one would be valid to pass to your method, neither of
those can map cleanly to -999.

s}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top