0

I have to call below method which has 2 parameter

public static byte[] readdata(string classtype, string msg)
{
    Encoding encoding = new System.Text.UTF8Encoding();
    string header = $"{classtype},{Guid.NewGuid().ToString()}";

    byte[] headerBytes = Encoding.UTF8.GetBytes(header);

    var test = JsonConvert.DeserializeObject<classtype>(msg);

i want to pass classtype to method DeserializeObject which i will get at runtime.

but parameter is generic i may get ClassA or ClassB or ClassC so how can i call method and pass generic class name which i'm getting it into string value?

readdata("ClassA" , "testmessage");
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 1
    You used the generic tag so why not a generic rather than passing a string? – Ňɏssa Pøngjǣrdenlarp Nov 11 '18 at 18:26
  • 2
    when the type `ClassA` is in scope of `readdata`, then it may be in scope of callers of `readdata` too, so why not pass the type instead of a string? If it must be a string, you can use `nameof(ClassA)`. To obtain a type from a string, look into reflection, for example [here](https://stackoverflow.com/q/179102/1132334) – Cee McSharpface Nov 11 '18 at 18:26
  • Then according to your last comment it is a possible duplicate of [Getting a System.Type from type's partial name](https://stackoverflow.com/questions/179102/getting-a-system-type-from-types-partial-name) – Cee McSharpface Nov 11 '18 at 18:37

1 Answers1

2

Not sure what you are trying but should not this work:

readdata(nameof(ClassA), "");
readdata(nameof(ClassB), "");
...

You could use the following overload JsonConvert.DeserializeObject

var test = JsonConvert.DeserializeObject(msg, Type.GetType("namespace.qualified.ClassA"));

Assuming you are passing generic type parameters - here is what you can try:

public static void readdata(string classtype, string msg)
{
    ///... your stuff
}

static void SendType<T>()
{
    readdata(typeof(T).Name, "");
}

static void Main(string[] args)
{
    SendType<ClassA>();
    SendType<ClassB>();
    SendType<ClassC>();
}

But i am not sure if the above will still solve your problem, you should try:

public static byte[] readdata<T>(string msg)
{
    //Your code
    var test = JsonConvert.DeserializeObject<T>(msg);
}

Calling statement:

readdata<ClassA>("Some message");
readdata<ClassB>("Some message");
readdata<ClassC>("Some message");

Suggest to read the following Type.GetType(“namespace.a.b.ClassName”) returns null

Sadique
  • 22,572
  • 7
  • 65
  • 91
  • i cannot do like this readdata("Some message"); because at runtime i'm getting value of class name. – Neo Nov 11 '18 at 18:36
  • Type.GetType works for me but it need `namespace.qualified.classname` full is there any other way to do it without a full specified? – Neo Nov 11 '18 at 18:47
  • 1
    @Neo - can you go to an Address if you only have the name of a city? I think you are doing something wrong. – Sadique Nov 11 '18 at 18:48