Home > Enterprise >  Dynamic class creation during method calling
Dynamic class creation during method calling

Time:11-26

I have an async function which has to be called multiple times but one the input parameters changes with each call.

public void ProcesAsyncReq((Class) validatedInputs, string data1, string data2...)
{
  //logic here is to just pass the validatedInputs to the dataprovider ,no changes whatsoever
}

while calling from different places, the (Class) changes, it can be example: Employee / Agency / etc Can we do that somehow ?

What I tried :

public class DataStore<T>
        {
            public T data { get; set; }
        }
public void ProcesAsyncReq(string className,string validatedInputs, string data1, string data2...)
{
     DataStore<className> gclass1 = new DataStore<className>(); /*throws error that it is a 
               variable but is used as a type*/
      gclass1.data=Newtonsoft.Json.JsonConvert.DeserializeObject(validatedInputs);
      //logic here is to just pass the validatedInputs to the dataprovider ,no changes whatsoever
}

CodePudding user response:

You can make your method generic as well:

public void ProcesAsyncReq<T>(string validatedInputs)
{
    DataStore<T> gclass1 = new DataStore<T>();
  
    gclass1.data = JsonConvert.DeserializeObject<T>(validatedInputs);
    ...
}

which you would call as follows:

ProcesAsyncReq<Employee>(myStringContainingSerializedEmployee);
  • Related