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;
}
}
}
}