none
Can we implement optional parameter in Generic method ? RRS feed

  • Question

  • Hi,

     I have a generic method (refer e.g.1) in my project. Just want to make T2 as optional parameter. So is there any way to call that method like below?

    GenericMethod<T1> ("Test", null);

    e.g.1

      public T1 GenericMethod<T1, T2>(string StrParam, T2 params = null) where T1 : new() where T2 : class, new()         {             return new Class1.ExecuteMethod<T1, T2>( StrParam, params);         }

    Thanks in advance

    Monday, July 29, 2019 10:01 AM

Answers

  • Hello,

    Seems the simple approach would be to have a overload method that does accept two parameters while the first accepts one parameter. Otherwise you will need to test for  default(T2).


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, July 29, 2019 11:00 AM
    Moderator
  • Hi Karen Payne,

                 Thank you so much for your valuable reply. yes, we can achieve this scenario by overloading that method. I tried other way to achieve this scenario easily by calling that method like below and it is working.

    GenericMethod<T1, Object> ("Test", null);

    Regards

    Arun Balakrishnan

    Wednesday, July 31, 2019 7:07 AM

All replies

  • Hello,

    Seems the simple approach would be to have a overload method that does accept two parameters while the first accepts one parameter. Otherwise you will need to test for  default(T2).


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, July 29, 2019 11:00 AM
    Moderator
  • Hi Karen Payne,

                 Thank you so much for your valuable reply. yes, we can achieve this scenario by overloading that method. I tried other way to achieve this scenario easily by calling that method like below and it is working.

    GenericMethod<T1, Object> ("Test", null);

    Regards

    Arun Balakrishnan

    Wednesday, July 31, 2019 7:07 AM