Home > Enterprise >  use field of generic list into class method
use field of generic list into class method

Time:01-09

I have several generic lists which have different quantity of properties, but all of them have some
common field names, for instance, id, port, name, and so on.

I have something like snippet.

public bool LookPortName<T>(List<T> list, string id, ref string port, ref string name)  
{
    int index;  
    try
    {    
      //It checks if found id into generic list.  
      if (index == -1) return false;                                        
      //Get portfolio abbreviation.                                             
      port = list[index].portfolio.Trim();  
      //Get portfolio complete name.  
      name = list[index].portName.Trim();   
      return true;  
    }
    catch
    {
      //Other code
    }
}  

Generic list into method

All lists have common files such as "id", "portfolio" and "portName" but they doesn't exist into generic
method.

Is it possible to use fields of generic list into generic method?

Someone who knows how to solve my question with a clear code example?

Thanks a lot!

CodePudding user response:

The common approach is to extract all common properties/methods into interface (or abstract class), implement this interface in the corresponding types (or inherit from the class) and then introduce the generic constraint limiting the allowed types to the interface (or abstract class):

public bool LookPortName<T>(List<T> list, string id, ref string port, ref string name)  
   where T : IHaveFields
{
    T x = ...;
    x.SomePropOnInterface;
}  

CodePudding user response:

Use a interface

// modify interface to fit your program
interface IPortfolio {
    public string Id { get; set; }
    public string portfolio { get; set; }
    public string portName { get; set; }
}

and add where T : IPortfolio to the method declaration This allows you to use T as if it were an IPortfolio.

public bool LookPortName<T>(List<T> list, string id, ref string port, ref string name) where T : IPortfolio

Then, have any class which needs to be passed into the method implement the interface

Note that you can't just use an interface because you wouldn't be able to pass a list.

More Info

  • Related