473,785 Members | 2,484 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting in a generic function

Hi,

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?

Thanks, Vin

// code
private void TestConvert()
{
string source = "1";
int destination = 0;
Parse(source, destination, new Converter<strin g, int>(Convert.To Int32));
}

static protected void Parse<Destinati on_type, Intermediate_ty pe>(string source,
Destination_typ e destination, Converter<strin g, Intermediate_ty peconverter)
{
Intermediate_ty pe test = converter.Invok e(source);
// Error on next line: Cannot convert type 'Intermediate_t ype' to 'Destination_ty pe'
destination = (Destination_ty pe)test;
}
Mar 28 '07 #1
3 4997
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.WriteLi ne(Parse<E,int> ("0", int.Parse));
Console.WriteLi ne(Parse<E,int> ("1", int.Parse));
Console.WriteLi ne(Parse<E,int> ("2", int.Parse));
}

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

-- Barry

--
http://barrkel.blogspot.com/
Mar 28 '07 #2
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:
Hi,
I know the example was a bit silly, but it was the simplest one I could get
the compile error on so I figured it'd be easier to display it that way.

Your solution works perfectly.

Thanks, Vin
Mar 28 '07 #3
I'm not entirely clear on what you are trying to do... but have you
perhaps looked into TypeConverter implementations ?

Marc
Mar 28 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

231
23247
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
4
25413
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the following error: Argument '1': cannot convert from 'GenericsPOC.ArticleCollection' to 'System.Collections.Generic.IList<object>' I tried casting specifically to IList<object> but then I get a runtime error: Unable to cast object of type...
22
13124
by: Adam Clauss | last post by:
OK, I have class A defined as follows: class A { A(Queue<B> queue) { ... } } Now, I then have a subclass of both classes A and B. The subclass of A (SubA), more specifically is passed a Queue<SubB>.
3
3656
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
3
2772
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from going through the process.
7
13706
by: S. Lorétan | last post by:
Hi guys, Sorry for this stupid question, but I don't know why it isn't working. Here is my (example) code: namespace Test { class A { public string Label1; }
28
16463
by: Peter Olcott | last post by:
I want to make a generic interface between a scripting language and native code, the native code and the interpreter will both be written in C++. The interpreter will probably be implemented as a subset of C/C++, thus will have the same syntax as C/C++. Somehow the interpreted code must be able to store generic function pointers because there is no way for the interpreter to know every possible function signature in advance. I was...
3
6004
by: =?Utf-8?B?TWlydHVs?= | last post by:
Hi I'm currently working with vbscripting through MSScriptControl. We have shared some of our objects that should be available for scripting. Some of the functions of these objects will return an interface to a class that must be cast to the appropriate higher level class to use all functionality. Thus I tried to implement a generic cast function for use from the vbscript
4
1434
by: casul | last post by:
Hi All, Given the following code that just defines a dummy class "my_class" and a dummy wrapper "my_wrapper" with a main program : #include <iostream> template< typename _Tag > class my_wrapper {
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.