locked
Generic Method that returns a generic type? RRS feed

  • Question

  • User711556406 posted

    Hi Everone.

    I would have loved to use a generic method that accepts a generic element (T) and returns the same (T). for instance :

    public T DoSometThing(T)

    {

        //Action Here...

        return T

    }

    Is is possiable?

    Monday, May 28, 2012 4:01 AM

Answers

  • User-661350001 posted

    yes its possible

    public T something(T arg) where T : class, new()

    {

    var g = default(T);

    return new T();

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 28, 2012 4:04 AM
  • User-661350001 posted

    it means T should be a class and new operator should be allowes (abstract class and private contructor) Type cannot be passed

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 28, 2012 4:34 AM

All replies

  • User-661350001 posted

    yes its possible

    public T something(T arg) where T : class, new()

    {

    var g = default(T);

    return new T();

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 28, 2012 4:04 AM
  • User711556406 posted

    Thanks.

    This Where T:class,new()

    What does new() mean?

    Monday, May 28, 2012 4:19 AM
  • User-661350001 posted

    it means T should be a class and new operator should be allowes (abstract class and private contructor) Type cannot be passed

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 28, 2012 4:34 AM
  • User711556406 posted

    Ok. Thanks a lot:)

    Monday, May 28, 2012 4:43 AM