jace
jace

Reputation: 1674

How to pass List<object> to method signature method(object obj) then cast back to List<object>

I have object List entity and I have to pass it to a method of a class with signature of method(object). It allows me to send a List to an object but how would I return it to object list of List?

E.G.

public class Sample
{
    public void passer()
    {
        List<ENT_Transaction> entityList = new List<ENT_Transaction>();
        ENT_Transaction entity = new ENT_Transaction;
        entityList.Add(entity);

        receiver(entityList);   
    }

    public void receiver(object obj)
    {
        //This is not allowed on runtime
        List<ENT_Transaction> entity = (List<ENT_Transaction>)obj;
    }
}

Am I doing it right or should I change the method signature to receiver(List obj) to receive a list of object List?

Upvotes: 0

Views: 306

Answers (1)

programtreasures
programtreasures

Reputation: 4298

As per your comment you have an interface which contains the function with object argument,

So I would recommend you to use generic

Create generic function in interface

interface ISample<T> where T : class
{
    void receiver<T>(T obj) ;
}

public class Sample : ISample<List<ENT_Transaction>>
{
    public void passer()
    {
        List<ENT_Transaction> entityList = new List<ENT_Transaction>();
        ENT_Transaction entity = new ENT_Transaction;
        entityList.Add(entity);

        receiver(entityList);
    }        

    public void receiver<T>(T obj)
    {
        T entity = obj;
    }
}

Upvotes: 2

Related Questions