Re: Casting in a generic function
- From: Barry Kelly <barry.j.kelly@xxxxxxxxx>
- Date: Wed, 28 Mar 2007 13:33:50 +0100
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/
.
- Prev by Date: Beginners Question About MIME Handling
- Next by Date: How to use MDI Child forms with a Docking toolbar
- Previous by thread: Security Software!!
- Next by thread: Re: Casting in a generic function
- Index(es):
Relevant Pages
|