none
What is the difference between generic classes and their non generic counterpart? RRS feed

  • Question

  • here are two classes :

        class ProductProcessor
        {
            public Product ExtendName(Product p)
            {
                p.name = p.name + " The product";
                return p;
            }
        }
    
        class ProductProcessor<T> where T : Product
        {
            public T ExtendName(T p)
            {
                p.name = p.name + " The product";
                return p;
            }
        }
    what is the advantage of the generic class given that both classes have no performance penalties?

    Sunday, October 22, 2017 5:16 PM

All replies

  • https://www.codeproject.com/Articles/814768/CRUD-Operations-Using-the-Generic-Repository-Patte

    The generic Repository would be such a usage.

    Sunday, October 22, 2017 5:28 PM
  • I thiunk that using non-generic class, you can deal with Product and DerivedProduct. The same can be done with ProductProcessor<Product>. But using ProductProcessor<DerivedProduct>, you can limit it to accept DerivedProducts only, or inherited.

    Sunday, October 22, 2017 6:59 PM
  • Suppose that T (and p) is a child class of Product, let's call it DerivedProduct. If DerivedProduct contains a property "name" that does NOT override the "name" in Product (i.e., declared as "new name" to break inheritance), then the Generic would invoke the name in DerivedProduct, while the non-generic would invoke the name in Product.

    Sunday, October 22, 2017 7:12 PM
    Moderator
  • In that example, there is no advantage. Using the generic version just introduces unnecessary complication.

    Generics are mostly useful for collections like lists and arrays. This means you will hardly ever need to write your own generic classes, because the common collections are already provided.

    • Proposed as answer by Fei HuModerator Wednesday, October 25, 2017 8:11 AM
    Monday, October 23, 2017 2:26 AM