0
votes

In MyRequest class I have:

public static T RetrieveData<T>(Uri uri) where T : class, new()
{
        return requestData<T>(query);
}

The Uri returns an array of strings such as:

{

 "prop1": "JOHN",
 "prop2": "JULIE",
 "value": 9

}, 
{

 "prop1": "KATE",
 "prop2": "Ryan",
 "value": 8

}

This is how I call my method:

var obj = MyRequest.RetrieveData<MyObject[]>("http://.....");   

This is how MyObject is defined:

public class MyObject
    {
        public string prop1;
        public string prop2; 
        public double value; 
    }

And this is the error I get:

MyObject[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyRequest.RetrieveData(uri)'

I got the method to work just fine when I tweak the uri to return just an array of 1 element and call it:

var obj = MyRequest.RetrieveData<MyObject>("http://....."); 

instead of

MyObject[]

but I really need to use an array. Any thoughts?

2
Try List<MyObject> instead? Unfortunately there's not enough information here to answer fully.DavidG
Like a charm! Thank you very much. May add it as an answer if you like.Sami

2 Answers

2
votes

It happens becase type T[] is fixed size array and doesn't have parameterless constructor. It is obvious that fixed size array require this size. For example:

var foo = new bar[0];
var foo = new bar[123];
var foo = new bar[count];

You can't initialize something like this:

var foo = new bar[]();
var foo = new bar[];

So it is clear that new() quantifier can't be used with fixed size arrays.

1
votes

You should try deserialising to List<T> instead of an array as your JSON library (likely JSON.Net, but hard to guess from your code) requires the type to have a constructor. For example:

var obj = MyRequest.RetrieveData<List<MyObject>>("http://.....");