none
Return RRS feed

  • Question

  • I have this class who returns a Product object.
    However I have other objects who inherent from Product.

    So I need to change this class to convert to ANY object.
    How could I use generics here ?

    public static Product ReturnProductHome(int position) {
        ...
    }
    Friday, September 5, 2014 5:03 PM

Answers

  • The following generic method will return an object of any type T:

    public static T ReturnProductHome<T>(int position)
            {
                return default(T);
            }


    If you want the method to only accept Product types, you could specify a constraint:

    public static T ReturnProductHome<T>(int position) where T : Product
            {
                return default(T);
            }
    
    public class Product
        {
    
        }
    
        public class Dervied : Product
        {
    
        }
    


    Usage:

    var obj = ReturnProductHome<Dervied>(0);
    

    Please remember to mark helpful posts as answer. and/or helpful.

    • Proposed as answer by MDeero Sunday, September 7, 2014 8:14 AM
    • Marked as answer by Fred BaoModerator Monday, September 15, 2014 9:29 AM
    Saturday, September 6, 2014 11:39 AM

All replies

  • I have this class who returns a Product object.
    However I have other objects who inherent from Product.

    So I need to change this class to convert to ANY object.
    How could I use generics here ?

    public static Product ReturnProductHome(int position) {
        ...
    }

     class Category<T>
        {
            public T _Name;
            public T Name
            {
                get { return _Name; }
                set { _Name = value; }
            }
        }   

    Saturday, September 6, 2014 3:01 AM
  • The following generic method will return an object of any type T:

    public static T ReturnProductHome<T>(int position)
            {
                return default(T);
            }


    If you want the method to only accept Product types, you could specify a constraint:

    public static T ReturnProductHome<T>(int position) where T : Product
            {
                return default(T);
            }
    
    public class Product
        {
    
        }
    
        public class Dervied : Product
        {
    
        }
    


    Usage:

    var obj = ReturnProductHome<Dervied>(0);
    

    Please remember to mark helpful posts as answer. and/or helpful.

    • Proposed as answer by MDeero Sunday, September 7, 2014 8:14 AM
    • Marked as answer by Fred BaoModerator Monday, September 15, 2014 9:29 AM
    Saturday, September 6, 2014 11:39 AM
  • Just exchange "return deafult(T)" with "return (T)list[position]" assuming you have a list "List<Product> list..." declared
    Sunday, September 7, 2014 8:17 AM