Click here to Skip to main content
15,901,505 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Friends,

Need a small help in writing one generic function that will take input value of two different type and return a value of another different type.

e.g public <t> Add<t,u,v>(U obj1, V obj2) where T:struct
{
}

Like sending a "int" and and "double" value and getting a "string" as output.Or Any combination of these basic types.

Please friends provide your valuable Ideas.

Thanking You
Posted
Comments
phil.o 6-Jan-14 6:28am    
And what did you try?
From the small sample you gave, we can see that you omitted the return type of the method.
Example:
public T Add<T,U,V>(U obj1, V obj2) where T:struct
{
}

Edit: if you want T to be string, then you cannot restrict it to a struct; strings are reference types.
somnath roy24 6-Jan-14 6:37am    
If i ommit the struct part i am unable to cast the integer or the double value to string. Can u please help me how to cast. I want to have

public Add<t,u,v>(U obj1, V obj2)
{
T temp;
temp=obj1.toString()+obj2.toString();
return temp;
}

it will be combination of basic types

1 solution

You can't do that - or not to those specifications. Sure you can add an int to a double and call ToString() on the result, but what if I pass an 'Exception' as the third parameter (or anything else which doesn't make sense)?

In order for generics to work, you need to constrain the generic parameters to a level where different acceptable types work the same way. A string is not compatible with int or double. It needs a special case 'ToString()' to make it work. How can you infer this needs doing in a generic manner for all types? You can't.

Perhaps your best bet would be to abandon Generics and just create a set of overloads for the different types you expect.
 
Share this answer
 
Comments
somnath roy24 6-Jan-14 6:45am    
If You are asked not to add but to set an example where two different types of variables will be sent as input parameters and the value returned will be of another type. Basically it was an interview question.
Rob Philpott 6-Jan-14 7:39am    
Well it doesn't make sense to me to take three types and combine the first and second into the third. Because you don't know what the operation is and how can I convert a string into UserControl? Sure you can create something which adds an int and double and returns a string, but that's a specific case not a generic case.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900