I try to figure out how I can access a static method within CallMe<T>() of class DoSomething. Is reflection the only solution here? I do not want to instantiate an object of type MyAction. Also if doing it through reflection is there a way to create the method through reflection within the method CallMe<T>() just once and then calling it many times to perform multiple operations on the same "reflected" method? Or is there any better way than through reflection? I basically want to create template implementation style classes such as MyAction that define how byte[] DoThis(string text) performs its duty. The AskForSomething() will then specify which template is being used and according to that the CallMe<T>() will go about its work. 
    public class AskSomething
    {
        public void AskForSomething()
        {
            DoSomething doSomething = new DoSomething();
            doSomething.CallMe<MyAction>();
        }
    }
    public class DoSomething
    {
        public void CallMe<T>()
        {
            Type type = typeof(T);
            //Question: How can I access 'DoThis(string text)' here?
            //Most likely by reflection? 
        }
    }
    public class MyAction
    {
        public static byte[] DoThis(string text)
        {
            byte[] ret = new byte[0]; //mock just to denote something is done and out comes a byte array
            return ret;
        }
    }
                Generics overview Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes.
Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);
Example: Create a Generics Method Here, the type parameter <T> is inserted after the modifier public and before the return type void . We can call the generics method by placing the actual type <String> and <Integer> inside the bracket before the method name. demo. <String>genericMethod("Java Programming"); demo.
We use <T> to create a generic class, interface, and method. The T is replaced with the actual type when we use it.
Define an interface with DoThis, have MyAction implement it, and constrain the T type parameter to be an instance of it with where T : IMyInterface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With