Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi.

To be very brief, I get the error saying "cannot convert from type T to int, or to double ......"
here is the code

public class Class1<t>
{
    public Func<t> getter;

    public Class1(Func<t> getter)
    {
        this.getter = getter;
    }
}

public class Class2
{
    public Class1<bool> boolData;
    public Class1<int> intData;
    public Class1<long> longData;
    public Class1<float> floatData;
    public Class1<double> doubleData;
    public Class1<string> stringData;

}

public class Main
{
    public Class2 data;

    public void TryMe<t>(Func<t> getter)
    {
        if(typeof(T) == typeof(int))
        {
            data.intData = new Class1<int>(getter);
            // ABOVE LINE

        }
        else if(typeof(T) == typeof(double))
        {
            data.intData = new Class1<double>(getter);
        }
        // and so on for bool, long, float and string
    }
}


[edit]Code block inserted to preserve formatting. "<" and ">" characters escaped to preserve meaning... - OriginalGriff[/edit]
Posted
Updated 23-Sep-10 6:44am
v2

1 solution

When you apply copy-paste... be sure to update all relevant items. ;)

data.intData = new Class1<double>(getter);

You are putting a class1 double into the intData placeholder.
 
Share this answer
 
Comments
barbarini 24-Sep-10 16:44pm    
my mistake... the line shoud be:
data.doubleData = new Class1"<double>"(getter);
but still I get the same error.... ?????
E.F. Nijboer 25-Sep-10 13:34pm    
Your way of using generics is a bit strange to be honestly. You are using a template type to store a template type parameter into a pre typed template typed property. So, instead of finding what is wrong here, it would be more interesting to implement it somewhat more effective. A template is used to store any type into the same placeholder instead of all kinds of placeholders of pre typed templates.

public class Class1
{
public Func<t> getter;

public Class1(Func<t> getter)
{
this.getter = getter;
}

public int getInt()
{
if(typeof(T) == typeof(int))
{
return getter;
} else
{
return 0;
}
}

You could fill this with more conversions and also implement automatic casting between types. There are also sophisticated methods to do that but for now this is a nice start.

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