generics problem

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



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


.



Relevant Pages

  • Re: Abnormal program termination
    ... foo.c:4: warning: function declaration isn't a prototype ... Your version is legal under C90 rules, but int mainis more explicit ... float ave(), average; ...
    (comp.lang.c)
  • RTF Render with Scale
    ... float fHorzSizeInches = nHorzSize / 25.4f; ... IntPtr hdc = graphics.GetHdc; ... int nHorzSize = SafeNativeMethods.GetDeviceCaps(hdc, ... PHYSICALWIDTH = 110, ...
    (microsoft.public.dotnet.languages.csharp)
  • (part1b) Han from China teaches you C
    ... int flist, mlist, slist; ... float board_size; ... static void draw_tube(float bottom_radius, float top_radius, ... glVertex3f(xmin, ymin, zmax); glVertex3f; ...
    (comp.lang.c)
  • Found a solution so far?
    ... float fHorzSizeInches = nHorzSize / 25.4f; ... IntPtr hdc = graphics.GetHdc; ... int nHorzSize = SafeNativeMethods.GetDeviceCaps(hdc, ... PHYSICALWIDTH = 110, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: RAD vs. performance
    ... work with both int and float. ... name (e.g. "+" for both int and float addition). ... Again, it's a compatibility issue. ... contend that assuming interfaces are equivalent and inferring the most ...
    (comp.lang.misc)