MohanRajNK
MohanRajNK

Reputation: 895

Pass class as a parameter to method

I'm having trouble finishing this method. How can I pass class as parameter and return the same class? This is the scenario I've met

Class A
{
...
}

Class C
{
 ....
}

Class B
{
  A a = getJSONClass(String jsonString, classA?);
  C c = getJSONClass(String jsonString, classC?);

  public (class?) getJSONClass(String jsonString, class?)
  {
   MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
   DataContractJsonSerializer ser = new DataContractJsonSerializer(class?.type);
   return ser.ReadObject(memoryStream) as class?;
  }

}

Any help??

Upvotes: 0

Views: 135

Answers (3)

D Stanley
D Stanley

Reputation: 152491

Well syntactically you'd use generics:

public T getJSONClass<T>(String jsonString) where T : class
{
   MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
   DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
   return ser.ReadObject(memoryStream) as T;
}

usage:

A a = getJSONClass<A>(String jsonString);
C c = getJSONClass<C>(String jsonString);

Upvotes: 3

Marcos Arruda
Marcos Arruda

Reputation: 742

Can't you do something like:

Class A
{
...
}

Class C
{
 ....
}

Class B
{
  A a = (A)getJSONClass(String jsonString, typeof(A));
  C c = (C)getJSONClass(String jsonString, typeof(C));

  public object getJSONClass(String jsonString, Type type)
  {
   MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
   DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
   return ser.ReadObject(memoryStream);
  }
}

Upvotes: 1

Dmitry Popov
Dmitry Popov

Reputation: 398

Use generics:

    public T GetDeserializedObject<T>(string jsonString) where T: class
    {
        var serializer = new DataContractJsonSerializer(typeof(T));

        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
        {
            return serializer.ReadObject(stream) as T;
        }
    }

Upvotes: 1

Related Questions