kintela
kintela

Reputation: 1323

confuse with generic parameters in C#

I'm trying something like this

enter image description here

I use it here

cliente

that is, I pass to Generic Method Print a list of Persons but inside the method, in data, I only have the standard methods of an object without any type.

How can I iterate the different kind of lists I will pass it?

Regards

Upvotes: 1

Views: 470

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

When you have a generic method without any constraint you say: this method works for any type, be it an int, string or even any arbitrary type like MyType. This is usually not what you actually want.

Instead you seem to have a very specific requirement: not just any type, but only a few very specific ones. In order to describe those specific types you can add a generic constraint. In your case the data-parameter seems to allways be some collection, e.g. a list, so let´s update your signature a bit:

public int Print<T>(string concepto, List<T> data) { ... }

Now you still have the same problem. You still have no specifics on what the elements within the list look like. They can still be numbers, strings, dates or whatever. You can now use this in your Print:

public int Print<T>(string concepto, List<T> data)
{
    foreach(var element in data) ... // element is of type T which is object
}

Actually you know that only a few types are possible, e.g. only Person. Ideally those types implement a common interface which you could use for the generic constraint:

public int Print<T>(string concepto, List<T> data) { ... } where T: MyInterface

This assumes all your possible types implement MyInterface:

class Person : MyInterface { ... }

Now you can access every member that is defined for that interface within your print-method:

public int Print<T>(string concepto, List<T> data) where T: MyInterface
{
    foreach(var element in data)
    {
        var myMember = element.MyMember; // element is of type T which is MyInterface
    }
}

Upvotes: 3

rjs123431
rjs123431

Reputation: 688

Modify your Print method to accept a generic type:

public int Print<T>(string concepto, IEnumerable<T> data)
{

}

Then, when you call it, pass the type, Person in this case:

 var result = repository.Print<Person>("subcontrationes", lista);

Upvotes: 2

Related Questions