We help IT Professionals succeed at work.
Get Started

Making a method more generic with T and interface

David DB
David DB asked
on
45 Views
Last Modified: 2020-02-21
Hi.

I have a method in C#  that I would like to be more generic.

public List<T> Test<T>(DateTimeOffset afterDate) where T:IType
      {
         string afterCursor = null;
         T data;
         bool morePages = false;
         List<T> retData = new List<T>();

         do
         {
            data = GetData<T>(afterCursor);
            if (data != null)
            {
               foreach (var item in data.Orders.Edges)
               {
                  afterCursor = item.Cursor;
                  retData.Add(item.Node);
               }
               morePages = data.Orders.PageInfo.HasNextPage;
            }
            else return null;
         } while (morePages);
         return retData;
      }

Open in new window


The IType interface is a collection of Orders, Customers and Products classes.

PS: The reason for using the Interface is to restrict the T types. If there is a better way, please let me know.  

The class structure on the top is the same, except for the property Orders. It's called Customers in Customers, and Products in Products. So the data.Orders.Edges will be data.Customers.Edges for Customers, and data.Products.Edges for Products.

So the name after data is the only thing that will change in this method. The rest is the same (Edges, PageInfo etc)

How can I accomplish this  so that it can be used for Orders, Customers and Products?

I know about checking if T is Orders, Customers or Products.
Comment
Watch Question
Commented:
This problem has been solved!
Unlock 1 Answer and 1 Comment.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE