locked
Generic Type As Optional Parameter. RRS feed

  • Question

  • Hi All

    Is there a way I could pass a Generic Type as Optional Parameter to a C# Method ? 

    Regards

    Anu


    Anu Viswan : www.AnuViswan.blogspot.com

    Saturday, February 7, 2015 1:05 PM

Answers

  • Change null to default(T) (null is not valid if T is a value type):

    private void MyMethod<T>(int Param1, T SampleClassObject = default(T))
            {
    
            }

    The other option is to contrain T to be a reference type:

    private void MyMethod<T>(int Param1, T SampleClassObject = null) where T : class
            {
    
            }
    

    But then you can not use the method for value types such as int, double, etc.

    Please remember to close your threads by marking helpful posts as answer and start a new thread if you have a new question.

    • Edited by Magnus (MM8)MVP Saturday, February 7, 2015 3:11 PM Constraint
    • Marked as answer by Kristin Xie Monday, February 16, 2015 10:21 AM
    Saturday, February 7, 2015 2:49 PM

All replies

  • In order to avoid misinterpretation, could you show an example of such functions?

    Saturday, February 7, 2015 1:56 PM
  • Do you mean something like this?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Type passType = typeof(string);
                myMethod(passType);
            }
    
            static void myMethod(Type type)
            {
                if (type == typeof(string))
                {
                }
            }
        }
    }
    


    jdweng

    Saturday, February 7, 2015 2:12 PM
  • Hi 

    Sorry I wasn't clear about it.

    Here is something which I am trying about it.

    void MyMethod<T>(int Param1, T SampleClassObject = null)

    Thanks

    Anu


    Anu Viswan : www.AnuViswan.blogspot.com

    Saturday, February 7, 2015 2:45 PM
  • Change null to default(T) (null is not valid if T is a value type):

    private void MyMethod<T>(int Param1, T SampleClassObject = default(T))
            {
    
            }

    The other option is to contrain T to be a reference type:

    private void MyMethod<T>(int Param1, T SampleClassObject = null) where T : class
            {
    
            }
    

    But then you can not use the method for value types such as int, double, etc.

    Please remember to close your threads by marking helpful posts as answer and start a new thread if you have a new question.

    • Edited by Magnus (MM8)MVP Saturday, February 7, 2015 3:11 PM Constraint
    • Marked as answer by Kristin Xie Monday, February 16, 2015 10:21 AM
    Saturday, February 7, 2015 2:49 PM