473,597 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic methods..

Ram
Hi All,

I am new to this Generics. I started with a Generic method which
doesn't return any value. It worked well.

Then I tried to write a generic method which will sum up the given
values and return the result. This is the piece of code.

private T Add<T>(T a, T b)
{

T c = a + b;
return c;
}

While compilation, I am getting the following error.

" Operator '+' cannot be applied to operands of type 'T' and 'T' ".

What is the problem?. How to perform operations on the Generic
variables?

How to write generic methods that will return a value?

Please throw some light on this.

Thanks in advance.
Regards,
Ram

Mar 15 '07 #1
4 2122
A common question. Generics are not like C++ templates, and the short
answer is that you can't use operator overloads (such as +, -, etc)
with gnerics. You can use other constraints, however, such as
"implements <xinterface", "is reference-type", "has a default
colnstructor". They are very useful, but not directly in your scenario
I'm afraid.

Marc

Mar 15 '07 #2
True. There are some things that can be done but not the C++ way at all.

For example your Add *could* check common types and behave as the best.
The only thing is that if someone calls the function with a type you have
not implemented (say Add<Form>), it will not work.

public class Template
{
public T Add<T>(T a1, T a2) where T:class
{
if (a1 is string && a2 is string)
{
return string.Concat(a 1, a2) as T;
}
else if (a1 is int && a2 is int)
{
return (Convert.ToInt3 2(a1) + Convert.ToInt32 (a1)) as T;
}

return default(T);
}
}

static void Main(string[] args)
{
Template x = new Template();
int v = (int)x.Add<obje ct>(2, 3);
}
"Marc Gravell" <ma**********@g mail.comha scritto nel messaggio
news:11******** *************@y 66g2000hsf.goog legroups.com...
>A common question. Generics are not like C++ templates, and the short
answer is that you can't use operator overloads (such as +, -, etc)
with gnerics. You can use other constraints, however, such as
"implements <xinterface", "is reference-type", "has a default
colnstructor". They are very useful, but not directly in your scenario
I'm afraid.

Marc

Mar 15 '07 #3
This example would be better handled with overloading. The whole point
of generics is that you *expect* it to be called for typed you don't
know about; also - unless I am very mistaken it can't work with int
because of the T : class

public int Add(int a1, int a2) {return a1 + a2;}
public string Add(string a1, string a2) {return a1 + a2;} // Concat by
the compiler
etc

Marc

Mar 16 '07 #4
A true generic implementation must support types that don't exist in
the (base) library wrapping the code. Maybe I am overcomplicatin g
things, but you could do this via interfaces etc as follows. You could
add a few more "standard" implementations , but more importantly the
end-developer can hook their own definitions for complex, quoternian,
SomeClass, SomeStruct, etc...

Anyways, here it is: (this is just a demo... not production code)

using System;
using System.Collecti ons.Generic;
using System.Text;
static class Program {
static void Main() {
Console.WriteLi ne(Foo(1, 4, 6));
Console.WriteLi ne(Foo(12.0F, 1.2F, 6F));
Console.WriteLi ne(Math.Add("ab c","def", "ghi"));
try {
Console.WriteLi ne(Foo("abc", "def", "ghi"));
} catch (Exception ex) {
Console.WriteLi ne(ex.Message);
}
}
static T Foo<T>(T arg1, T arg2, T arg3) {
return (Math.Product(M ath.Add(arg1, arg2), arg3));
}

}
public interface IMath<T{
T Add(T lhs, T rhs);
T Add(params T[] args);
T Product(T lhs, T rhs);
T Product(params T[] args);
T Negate(T arg);
T Invert(T arg);
T Unit { get;}
T Zero { get;}
// etc
}
public abstract class MathBase<T: IMath<T{
protected T ThrowNotSupport ed(string name) {
throw new NotSupportedExc eption(name + " is not supported for
" + typeof(T).FullN ame);
}
virtual public T Add(params T[] args) {
if (args == null) throw new ArgumentNullExc eption("args");
IMath<Tprovider = Math<T>.Default ;
switch(args.Len gth) {
case 0: return provider.Zero;
case 1: return args[0];
case 2: return provider.Add(ar gs[0], args[1]);
}

T value = provider.Add(ar gs[0], args[1]);
for (int i = 2; i < args.Length; i++) {
value = provider.Add(va lue, args[i]);
}
return value;
}
virtual public T Product(params T[] args) {
if (args == null) throw new ArgumentNullExc eption("args");
IMath<Tprovider = Math<T>.Default ;
switch(args.Len gth) {
case 0: return provider.Unit;
case 1: return args[0];
case 2: return provider.Produc t(args[0], args[1]);
}

T value = provider.Produc t(args[0], args[1]);
for(int i = 2; i < args.Length ; i++) {
value = provider.Produc t(value, args[i]);
}
return value;
}
virtual public T Add(T lhs, T rhs) {
return ThrowNotSupport ed("Add");
}
virtual public T Product(T lhs, T rhs) {
return ThrowNotSupport ed("Product");
}
virtual public T Negate(T arg) {
return ThrowNotSupport ed("Negate");
}
virtual public T Invert(T arg) {
return ThrowNotSupport ed("Invert");
}
virtual public T Unit {
get { return ThrowNotSupport ed("Unit");}
}
virtual public T Zero { // this is actually a reasonable default
implementation
get { return default(T); }
}
}
internal static class Math<T{ // avoid using the dictionary on each
access
private static readonly IMath<Tprovider ;
public static IMath<TDefault { get { return provider; } }
static Math() {
provider = Math.GetHandler <T>();
}

}
public static class Math {
public static T Add<T>(T lhs, T rhs) {
return Math<T>.Default .Add(lhs, rhs);
}
public static T Add<T>(params T[] args) {
return Math<T>.Default .Add(args);
}
public static T Product<T>(T lhs, T rhs) {
return Math<T>.Default .Product(lhs, rhs);
}
public static T Product<T>(para ms T[] args) {
return Math<T>.Default .Product(args);
}
public static T Negate<T>(T arg) {
return Math<T>.Default .Negate(arg);
}
public static T Invert<T>(T arg) {
return Math<T>.Default .Invert(arg);
}
public static T Unit<T>() {
return Math<T>.Default .Unit;
}
public static T Zero<T>() {
return Math<T>.Default .Zero;
}

static Math() {
providers = new Dictionary<Type , object>();
AddProvider<int >(new MathInt32Provid er());
AddProvider<flo at>(new MathSingleProvi der());
AddProvider<str ing>(new MathStringProvi der());
}
internal sealed class MathInt32Provid er : MathBase<int{
override public int Add(int lhs, int rhs) {return lhs + rhs;}
override public int Product(int lhs, int rhs) { return lhs *
rhs; }
override public int Negate(int arg) { return -arg; }
override public int Invert(int arg) { throw new
NotSupportedExc eption(); }
override public int Unit { get { return 1; } }
}
internal sealed class MathSingleProvi der : MathBase<float{
override public float Add(float lhs, float rhs) { return lhs +
rhs; }
override public float Product(float lhs, float rhs) { return
lhs * rhs; }
override public float Negate(float arg) { return -arg; }
override public float Invert(float arg) { return 1.0F / arg; }
override public float Unit { get { return 1.0F; } }
}
internal sealed class MathStringProvi der : MathBase<string {
override public string Add(string lhs, string rhs) { return
lhs + rhs; }
override public string Zero { get { return ""; } }
public override string Add(params string[] args) {
if (args == null) throw new ArgumentNullExc eption("args");
switch (args.Length) {
case 0: return "";
case 1: return args[0];
case 2: return string.Concat(a rgs[0], args[1]);
case 3: return string.Concat(a rgs[0], args[1],
args[2]);
case 4: return string.Concat(a rgs[0], args[1],
args[2], args[3]);
}
StringBuilder sb = new StringBuilder() ;
foreach (string arg in args) {
sb.Append(arg);
}
return sb.ToString();
}
}
static readonly Dictionary<Type , objectproviders ;
public static void AddProvider<T>( IMath<Tprovider ) {
if(provider==nu ll) throw new
ArgumentNullExc eption("provide r");
lock (provider) {
providers.Add(t ypeof(T), provider);
}
}
internal static IMath<TGetHandl er<T>() {
lock (providers) {
object provider;
if (!providers.Try GetValue(typeof (T), out provider)) {
throw new NotSupportedExc eption("No IMath<Tprovider
exists for " + typeof(T).FullN ame);
}
return (IMath<T>)provi der; // cast is OK since it made it
in
}
}
}
Mar 16 '07 #5

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

Similar topics

3
2886
by: Jim Newton | last post by:
hi all, i'm relatively new to python. I find it a pretty interesting language but also somewhat limiting compared to lisp. I notice that the language does provide a few lispy type nicities, but some very important ones seem to be missing. E.g., the multiple class inheritance is great, but there are no generic functions (at least that i can find). If i have classes X, Y, and Z, and subclasses X_sub, Y_sub, and Z_sub respectively.
3
2313
by: SimonH | last post by:
Hi all, I would like to make a generic set of methods that could be called regardless of the database behind the scenes. One of the methods I would like would take a string sql statement and an array of DataParameter objects. The problem i have is there doesnt seem to be a generic DataParameter class that I can instantiate. There only seems to be specific implementations like
2
3303
by: ljlevend | last post by:
I've noticed that in VS.NET 2.0 Beta 1 that none of the methods in System.Collections.Generic.List are overridable. In my app I currently have over 50 strongly typed ArrayLists that inherit from System.Collections.ArrayList. Each of these types raise strongly typed events for when items are added and removed (e.g., AddingItem, AddedItem, CollectionChanged, etc.). One of my hopes for v2.0 was to create a single generic List that replaces...
3
2753
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.
0
1641
by: Mikkel Blanné | last post by:
I haven't been able to find any references to using this combination of technologies (remoting + generic methods + method overloading). I don't think the problem has to do with C#, but I couldn't find a more appropriate place to ask... When I remotely try to call one of the methods in the object below, I get an exception. public class TestObj : MarshalByRefObject {
9
5837
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
13
3809
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...
10
2704
by: phancey | last post by:
I'm quite new to generics. I have 2 generic classes: MyClass<Tand MyOtherClass<T>. MyClass<Thas 2 public Add methods Add(MyOtherClass<T>); Add(MyOtherClass<Wrapper<T>>); (Wrapper<Tis another class that contains an object of type T) I have a third generic class: MyHandler<Twhich contains 2 Add methods and a generic method: Add(T obj)
26
3604
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
2343
by: =?Utf-8?B?TW9ydGVuIFdlbm5ldmlrIFtDIyBNVlBd?= | last post by:
"Anders Borum" wrote: Hi Anders, I'm afraid the GetMethod() does not currently support filtering on generic parameters so you will have to loop through the existing methods using GetMethods() MethodInfo methods = t.GetMethods();
0
7969
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
8272
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
8381
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
8258
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
6688
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
5847
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
3886
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...
1
2404
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
1
1494
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.