Senthil.Elayappan

In the below code snippet, i am trying to retun a int type from a Generic Method Add, but getting a compiler error "Cannot convert type 'int' to 'T' " I have a scenario in my project to have such implementation.

Would you give me your suggestion Do we have any workaround to implement this functionality

public class GenericCalculator

{

public GenericCalculator()

{

}

public T Add<T>(T t1, T t2)

{

if (t1 is int)

{

object n1 = (object)t1;

object n2 = (object)t2;

int i = ((int) n1) +( (int) n2);

return i;

}

}

}

GenericCalculator c = new GenericCalculator();

c.Add<int>(10,20);

Thanks,

Senthil



Re: Visual C# Language Generic Method Return Type Casting Problem

Alan M.

Well there several things about your code...

First off it doesn't make sense to use a generic as you are. Think about it, why would you use a generic, only to have specific type if statements inside your function.. "if(t1 is int)" etc.

What you should have done if you were going to have if statements for each type is to instead write an overloaded function.

public int Add(int left, int right);
public double Add(double left, double right);

Then... there would be no "if" statements, your code for each case would lie inside the method for the type.

Are you aware that you can override operators (define what the actual + operator does)
http://msdn2.microsoft.com/en-us/library/aa288467(VS.71).aspx


Now.. let me explain why your code doesnt' work. You are returning an integer type. (int i) however your method states it will return a generic T type. What you would need to do is....

return (T)i;

Which will cast it back to the generic type (int). Now keep in mind this doesn't make a lot of sense, and basically is a bad use of generics, however it will work.





Re: Visual C# Language Generic Method Return Type Casting Problem

Chuck the Code Monkey

Something like this may be what you are looking for:

public T Add<T>(T t1, T t2)
{
if (t1 == null)
throw new ArgumentNullException("t1");
if (t2 == null)
throw new ArgumentNullException("t2");

object n1 = t1,
n2 = t2;

if (t1 is byte)
return (T)((object)((
byte)n1 + (byte)n2));
if (t1 is short)
return (T)((object)((
short)n1 + (short)n2));
if (t1 is int)
return (T)((object)((int)n1 + (int)n2));
if (t1 is long)
return (T)((object)((
long)n1 + (long)n2));
if (t1 is float)
return (T)((object)((int)n1 + (int)n2));
if (t1 is double)
return (T)((object)((double)n1 + (double)n2));
if (t1 is long double)
return (T)((object)((long double)n1 + (long double)n2));

throw new InvalidOperationException("Type " + typeof(T).ToString() + " is not supported.");
}


However you will run into a substantial performance penalty resulting from boxing and unboxing (converting value types to reference types and then back to value types. If this is not performance critical code though, then all is well.





Re: Visual C# Language Generic Method Return Type Casting Problem

Senthil.Elayappan

return (T) i;

the above statements throws an compile time error " 'T' is a 'type parameter' but is used like a 'variable' "

please let me know if above code works in your machine

thanks





Re: Visual C# Language Generic Method Return Type Casting Problem

Senthil.Elayappan

thanks guys!!



Re: Visual C# Language Generic Method Return Type Casting Problem

James Curran

Due to the limitation of constraints on generics, you attempt is doomed to failure.

However, since you have the "if (t1 is int)" section in there, it seems your attempt is pointless as well.

It appears you'd be better off using overloading instead:

Code Snippet

public int Add(int t1, int t2)


{
return t1+t2;
}

public double Add(double t1, double t2)
{
return t1 + t2;
}
}

public T Add<T>(T t1, T t2)

{

// do something special for reference types without +


}






Re: Visual C# Language Generic Method Return Type Casting Problem

Solairaja

public class Sample
{
public Sample()
{

// nothing

}

public enum ReturnAs
{
Integer, Double
}

public T MyMethod<T>(ReturnAs key,T param1,T param2)
{
if (key == ReturnAs.Integer)
{
return ((T)(object)(Convert.ToInt32(param1) + Convert.ToInt32(param2)));
}
else if (key == ReturnAs.Double)
{
return ((T)(object)(Convert.ToDouble(param1) + Convert.ToDouble(param2)));
}
else
{
return ((T)(object)(0));
}
}
}

try this it will work.

dont forget to include the System.Collections.Generic Namespace in the .cs file

call the method as mentioned below..

Response.Write(Sample.MyMethod<double>(Sample.ReturnAs.Double, 32, 45));





Re: Visual C# Language Generic Method Return Type Casting Problem

Chuck the Code Monkey

Explicity specifying the type as an aditional parameter is redundant as you have the generic parameter which can tell you that. Also the type can be implied from the call so specifying <double> when calling the method is actually unnecessary.




Re: Visual C# Language Generic Method Return Type Casting Problem

:)Eric Han

return i as T maybe better.




Re: Visual C# Language Generic Method Return Type Casting Problem

Solairaja

Yea.. i understand that specifying the type in redundant manner not need..

but the first thread he tried to compare the T type and the Int type which will say that type "T" is used like a variable as compile time error..

which will can be overcome by the code which i have given

I accept its not the exact solution. but it will be a good & safe workaround.

if it not so.. plz let me know. chuk and try to test the code with different data type. i think it will work I consider.

Thank u

solai