Re: Casting in a generic function



Vincent Finn wrote:

I am trying to write a generic function and it isn't behaving as expected.

I want to avoid having to write custom convert functions for my enums so
I want to convert to an int and cast to the enum, this wouldn't compile so
I tried a few variations.
The cast fails inside the generic function even though its valid.
The code below is the simplest example of the problem I could think of, even
casting int to int fails.

Is this a limitation or am I doing something wrong?

Generics aren't like C++ templates. If an operation isn't explicitly
labeled as supported by a type argument via with a 'where' clause, it
will cause a compile-time error. Try casting to object first (to the
root of the inheritance hierarchy), then back down again (to avoid an
invalid cross-cast).

Your example doesn't make much sense. 'destination' is an argument
passed by value, so assigning to it has no effect. I'm trying to guess
what problem you're really trying to solve, and this is the best I could
come up with:

---8<---
using System;

class App
{
enum E
{
A, B, C
}

static void Main()
{
Console.WriteLine(Parse<E,int>("0", int.Parse));
Console.WriteLine(Parse<E,int>("1", int.Parse));
Console.WriteLine(Parse<E,int>("2", int.Parse));
}

static TEnum Parse<TEnum,TVia>(string text,
Converter<string,TVia> converter)
{
TVia value = converter(text);
return (TEnum) (object) value;
}
}
--->8---

-- Barry

--
http://barrkel.blogspot.com/
.



Relevant Pages

  • Re: Why do enum values req explicit conversions
    ... that an enum is definitely an instance of System.Enum - proven by the fact ... I suppose the most important issue is that the syntax of the cast operator ... is actually an unbox operation is incorrect. ... If it were already an int, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: help with statistics library
    ... Your always using an int for the sizes of the arrays you pass ... Some sources simply say "avoid comparing doubles for equality." ... E.g. if you divide a double by an int you don't have to cast the ... libraries header file. ...
    (comp.programming)
  • Re: Nullable Enum
    ... value - i.e. you cannot unbox float to int, or uint to int, or int to ... int, and are trying to unbox it to a different type, enum. ... Is there a way to achieve the type cast with a single statement? ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: enum as index for DataRow
    ... public constant int Table1.Field1 = 0; ... > from myfields to int. ... > I REALLY do not want to have to cast every use of this enum. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: enum is int
    ... if (te is int) ... conversions, boxing conversions, and unboxing ... I don't have Visual Studio handy at the moment, but I'm suspicious of the idea that a boxed enum would successfully be cast to an int. ...
    (microsoft.public.dotnet.languages.csharp)