Sending Generic Object

A

ADN

Hi, I have a method which calls my service factory:

class person
{
public int ID { get; set: }
public string Name {get; set;}
}

IList<Person> mypeople = __serviceFactory.Fetch(new Person())

Here is my generic method:

public List<T> Fetch<T>(T fetchobject)
{
Type __type = fetchobject.GetType();

// return a generic list of all of the people
IList<__type> myPeopleList = new IList<__type>();

myPeopleList = DataLayer.GetMyPeople(); // will return a
IList<Person>

return myPeopleList
}

I am getting an error when I try to cast the IList<type> because I
don't think you can do that. Is there a way I can pass in a generic
object and create a generic collection from a generic object?
 
J

John B

ADN said:
Hi, I have a method which calls my service factory:

class person
{
public int ID { get; set: }
public string Name {get; set;}
}

IList<Person> mypeople = __serviceFactory.Fetch(new Person())

Here is my generic method:

public List<T> Fetch<T>(T fetchobject)
{
Type __type = fetchobject.GetType();

// return a generic list of all of the people
IList<__type> myPeopleList = new IList<__type>();
IList<T> myPeopleList = DataLayer.GetMyPeople();
Or...
public List<T> Fetch<T>()
{
 
P

Pavel Minaev

Hi, I have a method which calls my service factory:

class person
{
     public int ID { get; set: }
     public string Name {get; set;}

}

IList<Person> mypeople = __serviceFactory.Fetch(new Person())

Here is my generic method:

public List<T> Fetch<T>(T fetchobject)
{
     Type __type = fetchobject.GetType();

     // return a generic list of all of the people
     IList<__type> myPeopleList = new IList<__type>();

     myPeopleList = DataLayer.GetMyPeople(); // will return a
IList<Person>

     return myPeopleList

}

I am getting an error when I try to cast the IList<type> because I
don't think you can do that. Is there a way I can pass in a generic
object and create a generic collection from a generic object?

You cannot pass Type values as generic parameters. But in your case, I
do not see why you'd even need to. First of all, would you be okay
with this?

public List<T> Fetch<T>(T fetchobject)
{
// return a generic list of all of the people
IList<T> myPeopleList = new IList<T>();
...
}

This doesn't use the actual run-time type of the passed object, but
rather the type of expression that was passed as an argument.

The second problem is that your generic method is not really generic -
here's why:

myPeopleList = DataLayer.GetMyPeople(); // will return a
IList<Person>

Well, if it can only handle lists of Person, then why are you trying
to make it generic in the first place?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top