user726720
user726720

Reputation: 1247

Error on returning Generic Type (No implicit Conversion)

Getting an implicit conversion exception when calling a generic method. What is the right way of doing this?

Here are my interface and class definitions:

public interface TestData
{
    string field { get; set; }
    string fieldName { get; set; }
    string type { get; set; }
}

public class TestClass
{
    public static T Call<T>(string Project, string type) where T : TestData
    {
        var returning = GETCG<T>(test, type);

        return (T)Convert.ChangeType(returning, typeof(T), CultureInfo.InvariantCulture);
    }

    private static T GETCG<T>(string test, string type) where T : TestData
    {
        var fields = nodees.Cast<XmlNode>().Select(x => new
        {
            // some data
        }).ToList();

        if (fields != null)
        {
            return (T) Convert.ChangeType(templateFields, typeof(T), 
                CultureInfo.InvariantCulture);
        }
        else
        {
            return (T)Convert.ChangeType("SomeString", typeof(T), 
                CultureInfo.InvariantCulture);
        }
    }
}

I'm getting the following exception:

The type 'System.Collections.Generic.List' cannot be used as type parameter 'T' in the generic type or method 'TestClass.Call(string, string)'. There is no implicit reference conversion from 'System.Collections.Generic.List' to 'Test.TestData'

On the line of code below:

var test = TestClass.Call<List<TestData>>("ProjName", "Audio");

If you see in the GETCG method I'm returning different types List and string. Methods Call and GETCG implement the interface TestData. Can I have an explanation why I'm getting this error and how can I improve this code keeping in mind I need to return both strings and List from the TestClass

Upvotes: 0

Views: 918

Answers (1)

Rufus L
Rufus L

Reputation: 37060

The problem here is that you've defined a constraint on T that it must implement the TestData interface, however you're declaring T as a List<TestData>.

The compiler is telling you that List<T> does not implement the TestData interface and there is no implicit conversion it can use to make that happen.

The solution would be to either remove the constraint or pass in a class instance that implements the TestData interface.

Upvotes: 0

Related Questions