user3520332
user3520332

Reputation: 241

Generic Type Methods

What are some practical cases of why I would need something like this:

  public void Show<FirstType, SecondType>(FirstType first, SecondType second)
  {
      //Do Something
  }

And not just this:

  public void Show(FirstType first, SecondType second)
  {
     //Do Something
  }

Thanks so much

Upvotes: 1

Views: 56

Answers (4)

BateTech
BateTech

Reputation: 6496

A good example of when you would want two generic parameters with different types is Dictionary<TKey, TValue>

http://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

Upvotes: 0

msmolcic
msmolcic

Reputation: 6557

I can give you a simple use of generics, for example, the method that compares two variables of the same type and returns true or false depending on the equality:

public static bool Equals<T>(T Variable1, T Variable2)
{
    return Variable1.Equals(Variable2);
}

This method is now reusable for any parameter type. T stands for type and is usually written this way, but not necessarily. Using this class you can compare equality of any type you define in your main method without boxing/unboxing types inside the method. Also your equality compare method is safe from wrong type input once you use it in your main method. Example of using this method would be something like this:

public static void Main(string[] args)
{
    if (VarCompare<int>(10, 10))
    {
        Console.WriteLine("Inputs are equal.");
    }
    else
    {
        Console.WriteLine("Inputs aren't equal.");
    }
}

By simply changing your if condition to VarCompare<string>("A", "B") you could compare two string types instead of integers.

Upvotes: 0

BradleyDotNET
BradleyDotNET

Reputation: 61339

This example comes from the framework, but the LINQ extension methods are implemented this way. For example, the signature for .Where is:

IEnumerable.Where<TSource> (IEnumerable<TSource>, Func<TSource, Boolean>);

This doesn't have two type arguments like your example, but shows a good use case for having one. The "Where" is not type specific, and because the predicate given later uses the same type argument you get type safety when performing comparisons.

This far preferable to a .Where for every possible type, hence the use of generics.

Upvotes: 2

AD.Net
AD.Net

Reputation: 13399

Because you'll need to create another method for something like this, which might be duplication in some cases. To avoid duplicating logic, you use generics when the types have some behavior in common. Also, it's typesafe so no need to box/unbox when you use generics.

public void Show(ThirdType third, FourthType fourth)
  {
     //Do Something
  }

Upvotes: 1

Related Questions