473,804 Members | 3,353 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

generic class with numeric type?

Is that not allowed to assume generic type numeric type? As far as I've
tried, I got an error with the following code:

public class AAA<T>
{
public int Foo(T a)
{
return a; // error: Cannot implicitly convert type 'T' to 'int'
}
}

public class BBB
{
public int Goo()
{
int x = 3;
return AAA<int>.Foo(x) ;
}
}

where my intention is to use AAA<on numeric value only, which is
acceptable in C++.

How can I resolve that compilation error? Please reply.
Thanks in advance.

Hyun-jik Bae
Oct 23 '06 #1
4 9176
Hyun-jik Bae wrote:
Is that not allowed to assume generic type numeric type? As far as
I've tried, I got an error with the following code:

public class AAA<T>
{
public int Foo(T a)
{
return a; // error: Cannot implicitly convert type 'T' to
'int' }
}

public class BBB
{
public int Goo()
{
int x = 3;
return AAA<int>.Foo(x) ;
}
}

where my intention is to use AAA<on numeric value only, which is
acceptable in C++.

How can I resolve that compilation error? Please reply.
Since .NET generics are fully compiled and represented in the IL, in order
for that IL to be verifiable (provably safe), there are limitations on what
..NET generics can do - they are severely limited compared to C++ templates
(and also have significant advantages compared to C++ templates in some
cases).

To use a type as a generic type parameter, when you write the generic class,
you specify constraints on the generic type parameters. These constraints
actually increase what you can do with the type. There are only two types
of constraints: a constructor contraint, written as new(), and an interface
constraint.

Unfortunately, there's no "IConvertsToInt " interface defined by the .NET
framework, and defining such an interface yourself would be unfulfilling at
best.

Your best bet in the example you supplied is probably to use the Convert
class

public class AAA<T>
{
public int Foo(T a)
{
return Convert.ToInt32 (a);
}
}

public class BBB
{
public int Goo()
{
int x = 3;
return AAA<int>.Foo(x) ;
}
}

Unfortunately, this will result in 'a' being boxed onto the managed heap,
since Convert.ToIn32 takes a parameter of type System.Object. But it will
work.

Doing arithmetic - even simple comparisions - with generic parameters is
hard. There are a couple of artibles on code project that explain the
limitations and what you can do to work around them.

Here's one of them - there's at least one other good one, but I couldn't
find it with a quick search.

http://www.codeproject.com/csharp/genericnumerics.asp

-cd

Oct 23 '06 #2
Hyun-jik Bae schrieb:
Is that not allowed to assume generic type numeric type? As far as I've
tried, I got an error with the following code:

public class AAA<T>
{
public int Foo(T a)
{
return a; // error: Cannot implicitly convert type 'T' to 'int'
}
}

public class BBB
{
public int Goo()
{
int x = 3;
return AAA<int>.Foo(x) ;
}
}

where my intention is to use AAA<on numeric value only, which is
acceptable in C++.

How can I resolve that compilation error? Please reply.
Thanks in advance.

Hyun-jik Bae
you can specify what type the generic type should be.

public class AAA<T>
where T: int
{
public int Foo(T a)
{
return Convert.ToInt32 (a);
}
}

have a look to "where T ....". then you can do something like

public T Foo(T a)
{
return a;
}

or

public int Foo(T a)
{
return (int)a;
}

depends on what the method in praxis should do.
hope this helps.

cheers,
marc

Oct 23 '06 #3
"Marc" <ma**@idev.ch a écrit dans le message de news:
11************* *********@e3g20 00...legro ups.com...

| you can specify what type the generic type should be.
|
| public class AAA<T>
| where T: int
| {
| public int Foo(T a)
| {
| return Convert.ToInt32 (a);
| }
| }

This is not possible, you really need to check suggestions before posting
answers :-)

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Oct 23 '06 #4

Joanna Carter [TeamB] schrieb:
This is not possible, you really need to check suggestions before posting
answers :-)
yes, you are right.
just wanna point to the "where" keyword for generics where one can
limit the types that can be used for a generic. this could help here
but it depends on the concrete implementation of the methods and their
results. i mean, does it always need to be an int or just the same as
the generic type?

cheers,
marc

Oct 23 '06 #5

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

Similar topics

4
391
by: Tom Jastrzebski | last post by:
Hello everybody, Here is the problem I came across experimenting with Generics. I would like to write a class or a struct adding integer to any other, initially undefined *numeric type*. So, my struct would look more or less like: struct MySum<T> where T : struct { public static T AddInteger(T value, int i) { return value + i;
1
1385
by: Arthur Dent | last post by:
Hi all... Heres what im looking to do.... I have a Generic class i wrote. Now, on another class, i want to add a method which can take in an object of my generic class... but the catch is, i want it to be able to take in an instance of the generic REGARDLESS of what the "Of" type of the generic is. E.g. .... given a generic class MyGen(Of T) I want to be able to write another class as such:
5
2179
by: dvir | last post by:
Hi I want to declare a variable which is pointer to a class at my header. here is my header: base_functions.H ----------------------------- #ifndef BASE_FUNCTIONS_H #define BASE_FUNCTIONS_H
4
3244
by: Andrew Ducker | last post by:
I have a collection of classes descending from a single root class (let's call it RootClass). They all currently have a property of Logical, of type Logical. However they actually return a subclass of Logical (LogicalA, LogicalB). I'm currently casting them to the right type when I retrieve them, but obviously this isn't terribly 'nice'. I tried converting the class to be generic, and having a type parameter that affected the type of...
9
12856
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The natural (but illegal) notation would be something like class A<QueueClasswhere QueueClass :...
1
5043
by: bjwillykajilly | last post by:
Well, I got an assignment due this morning, so i guess ill end up turning it in a day late eh. anyways. I have a couple problems that I don't know what to do with. the objective is here: Write a generic class, MyStatisticsClass, with a type parameter T where T is a numeric object type (e.g., Integer, Double, or any class that extends java.lang.Number). Add a method named standardDeviation that takes an ArrayList of type T and returns as a...
10
1941
by: Egghead | last post by:
Hi all, Can someone kindly enough point me to some situations that we shall or "must" use Generic Class? I can foresee the Generic Method is powerful, but I can not find a single situation that I will need the Generic Class, given there are so many other options. -- cheers,
11
1905
by: Bob Altman | last post by:
Hi all, I want to write a generic class that does this: Public Class X (Of T) Public Sub Method(param As T) dim x as T = param >3 End Sub End Class
26
3632
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic delegate type expression in just the right place and a well-named method means we can almost read the code out loud and understand it without even thinking. Note that since 'boxing' and 'unboxing' is involved (I think), you don't get what you...
0
9711
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
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
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...
1
10331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7631
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
5529
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
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
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.