Search code examples
c#typesoverloadingoverload-resolution

Method Overloading with Types C#


I was wondering if the following is possible. Create a class that accepts an anonymous type (string, int, decimal, customObject, etc), then have overloaded methods that do different operations based on the Type. Example

    class TestClass<T>
{
  public void GetName<string>()
  {
      //do work knowing that the type is a string    
  }

  public string GetName<int>()
  {
      //do work knowing that the type is an int

  } 

  public string GetName<int>(int addNumber)
  {
      //do work knowing that the type is an int (overloaded)    
  } 

  public string GetName<DateTime>()
  {
      //do work knowing that the type is a DateTime

  } 

  public string GetName<customObject>()
  {
      //do work knowing that the type is a customObject type    
  }

}

So now I could call the GetName method, and because I already passed in the type when I initialized the object, the correct method is found and executed.

TestClass foo = new TestClass<int>();

//executes the second method because that's the only one with a "int" type
foo.GetName();

Is this possible or am I just dreaming?


Solution

  • What you're trying to do is possible like this:

    class TestClass<T>
    {
       public string GetName<T>()
       {
          Type typeOfT = typeof(T);
          if(typeOfT == typeof(string))
          {
              //do string stuff
          }
       }
    }
    

    While this is possible, you're kind of defeating the purpose of generics. The point of generics is when the type doesn't matter, so I don't think generics is appropriate in this case.