Since C# does not support static method in generic functions, what can I do instead

Question!

I am aware that C++ template is different than C# generics, so the following code will not work in C#...Nonetheless it shows what I want to achieve

class A{
   public static string getPlainTextKey(string jsonString)
   public static string produceJsonString(string encryptedKey)
}
// A and B knows two DIFFERENT Json Schema
class B{
   public static string getPlainTextKey(string jsonString)
   public static string produceJsonString(string encryptedKey)
}
// C performs the main operation, does not know about json detail
class C{
   string template<T>(string jsonString){
      string key = T.getplainTextKey(jsonString);
      return T.produceJsonString(encrypt(key));
   }
}

my first solution is to write an interface IJson that class A and class B implements, and the class C now looks like:

string template(string jsonString, IJson jsonHelper){
  string key = jsonHelper.getplainTextKey(jsonString);
  return jsonHelper.produceJsonString(encrypt(key));
}

However, I don't like this solution

  1. As you can see class A and class B are static classes, I don't want to create an object every time I use the template, the extra overhead is against my initial incentive
  2. On top of the object maintenance overhead...this solution present extra work at run time, it needs to determine which output() to call...since I am using polymorphism
  3. I couldn't find macro in C# either, so the closest workaround (with my original performance expectation)...is to duplicate code whenever I call template...and in my opinion this is also bad practice

EDIT:

1.template method is triggered via webAPI, which is the reason why I don't want to create an object per request...I can use SINGLETON to create instances when the class is loaded, this seems to be a perfect solution

2.using reflection instead of create IJson interface, I think this should have the same function lookup overhead as polymorphism but it doesn't have to deal with object creation

string template<T>(string jsonString){
  System.type type = typeof(T);
  string key = (string)type.GetMethod("getplainTextKey").
               Invoke(null,jsonString);
  return (string)type.GetMethod("produceJsonString"). 
         Invoke(null,encrypt(key));
}


This video can help you solving your question :)
By: admin