Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generics to pass argument to a non-generic method?

Tags:

c#

generics

Why does the following code not compile? How can I create a generic method which calls the appropriate "BitConverter.GetBytes" overload based on if the generic type is an "int", "bool", "char", etc.? More generally, how can I create a generic method which calls a non-generic method based on the generic parameter's type?

using System;

public class Test
{
    public static void Main()
    {
      var f = new Foo();
      f.GetBytes(10); // should call BitConverter.GetBytes(int);
      f.GetBytes(true); // should call BitConverter.GetBytes(bool);
      f.GetBytes('A'); // should call BitConverter.GetBytes(char);
    }
}

public class Foo
{
    public byte[] GetBytes <TSource> (TSource input)
    {
      BitConverter.GetBytes(input);
    }
}
like image 480
Kevin Carrasco Avatar asked Apr 23 '14 18:04

Kevin Carrasco


People also ask

Can you have a generic method in a non-generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

Can a generic class be a subclass of a non-generic class?

A generic class can extend a non-generic class.

Can we have generic method in non-generic class in C#?

We can have generic methods in both generic types, and in non-generic types. Our first example in Program 43.1 is the generic method ReportCompare in the non-generic class StringApp . ReportCompare is a method in the client class of String<T> which we encountered in Section 42.4.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.


1 Answers

More generally, how can I create a generic method which calls a non-generic method based on the generic parameter's type?

In general, you can't, unless the method in question takes System.Object as a parameter. The problem is that the generic isn't constrained to just types that would be allowed by the method call arguments.

The closest you can do is to use runtime binding:

public byte[] GetBytes <TSource> (TSource input)
{
     dynamic obj = input;
     BitConverter.GetBytes(obj);
}

This pushes the method binding logic to runtime, and will throw if there isn't an appropriate method to call.

like image 124
Reed Copsey Avatar answered Sep 18 '22 23:09

Reed Copsey