473,769 Members | 7,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

confusion about generics

I've read several documents about upcoming C# generics and I still cannot
understand one thing.

Would it be valid to write a code like this:

class SomeClass
{
public void AMethod<T>(T a, T b)
{
T c = a + b; // ?
...
}
}

since + is defined for some simple types and can be overloaded for reference
types, then what kind of constraint should be used to allow the + in above
context?

or would it be forbidden to use standard binary operators in generic code?
(in fact, it would require to have the interface, IAddable, make all numeric
types implement the interface and then add "where T : IAddable" to the above
code)

if it is forbidden to use + in above context, then how will I create a
generic class that acts like this one above? (suppose I need to call the
method AMethod with any class that supports + operation, including <int>
<double> and other numeric types).

I would really like to hear from an expert on this issue.
Thanks in advance.

Wiktor Zychla
Nov 15 '05 #1
2 2745
Wiktor,

The constraint mechanism doesn't define operators on the type as a
constraint. Because of this, you will have to get around it in some other
way. Like you specified, an interface which indicates that the operation
could be performed would be the best way to go.

Generally speaking, I think that using an operation for a constraint
would be a bad idea anyways, since not all .NET languages support operator
overloads (VB for example) and you would limit generics on those platforms.
However, interfaces are accessible in all languages (or at least, more
accessible than overloaded operators).

Because of this, you should have a constraint on an IAddable interface
and then use the Add method on that interface (I am guessing this would be
there).

But, this raises the problem of what do you do for already defined
classes which expose this functionality and can not be changed to implement
IAddable? In this case, you will have to check the type of T, and then find
the static method that corresponds to the operator overload (op_Addition).
If it exists, then you can call that through Reflection. I know it is
painful, but it is the only way with the way generics are currently
proposed.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Wiktor Zychla" <ie****@microso ft.com.no.spam> wrote in message
news:e8******** ******@TK2MSFTN GP12.phx.gbl...
I've read several documents about upcoming C# generics and I still cannot
understand one thing.

Would it be valid to write a code like this:

class SomeClass
{
public void AMethod<T>(T a, T b)
{
T c = a + b; // ?
...
}
}

since + is defined for some simple types and can be overloaded for reference types, then what kind of constraint should be used to allow the + in above
context?

or would it be forbidden to use standard binary operators in generic code?
(in fact, it would require to have the interface, IAddable, make all numeric types implement the interface and then add "where T : IAddable" to the above code)

if it is forbidden to use + in above context, then how will I create a
generic class that acts like this one above? (suppose I need to call the
method AMethod with any class that supports + operation, including <int>
<double> and other numeric types).

I would really like to hear from an expert on this issue.
Thanks in advance.

Wiktor Zychla

Nov 15 '05 #2
> But, this raises the problem of what do you do for already defined
classes which expose this functionality and can not be changed to implement IAddable? In this case, you will have to check the type of T, and then

find

this is exactly what I wanted to hear. as usual, thanks Nicholas.
regards, Wiktor
Nov 15 '05 #3

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

Similar topics

27
2462
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and still no can do... Any info would be great!
23
2552
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
12
2744
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as it defines the language more completely. Great to use.
1
1152
by: Epetruk | last post by:
Hello, I have a solution with two projects. One of the projects is called MyProj with a root namespace called MyProj.Obj. The single source (vb) file for MyProj has a class called Obj. There is no
9
5986
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
1
2438
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
13
3837
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
2
1282
by: joseph_gallagher | last post by:
Hi, I've been playing with generics and I was wondering if anyone could tell me why the following doesnt work, and if there is another way to do it public class A<Twhere T : B, new() { public B Get() { B b = new B(); b.X = this;
1
1001
by: Peter | last post by:
Hi I'm trying to call a C# Method from with VB.NET and am having all sorts of troubles as I'm new to Generics. The C# method (which I didn't develop) is as follows: /// <summary> /// Implementation of <c>Register(Action&lt;T&gt; handler)</c> method of <c>ISubscriptionService&lt;T&gt;</c> /// interface. Subscribes an action to be performed when a
0
9589
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
10049
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...
1
9997
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,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8873
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
7413
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
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
3565
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.