none
Making a method generic RRS feed

  • Question

  • Hello,

    I want to make following method generic for other attributes as well, like Product Id, ProductType, ProductCategory...i.e.I need to be able to pass any of these attributes as a parameter to this method and it should return the corresponding value from the collection.
    private string GetABC()
    {
        return myList.Select(x=>x.ProductName)
    }

    Is there any better way of achieving this in C# other than switch case please?

    Thanks.

    Friday, June 15, 2018 3:04 PM

All replies

  • I would say you don't need to. LINQ already has the select statement so putting a wrapper around it wouldn't gain you anything. Just use LINQ. If there are common queries you want to do then add extension methods instead that are focused on the specific details.

    public static class ProductExtensions
    {
       public static IEnumerable<Product> GetProductsByName ( this IEnumerable<Product> source, string productName )
       {
           return source.Select(x => x.ProductName == productName);
       }
    }

    In your specific example you have written a method that returns a property. Why would you do this vs just using the property directly.

    Product product = ...;
    
    //What does this gain you?
    var name = GetABC();
    
    //vs this
    var name2 = product.ProductName;

    Your method is actually a little confusing because you are using Select which returns back IEnumerable<string> but you're returning a string. This shouldn't even compile.

    As for the general question of making your method generic then yes you could but, again, why?

    //Not tested
    private T Get<T> ( Func<Product, T> getter )
    {
       return myList.Select(getter).FirstOrDefault();
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, June 15, 2018 6:21 PM
    Moderator