TheBigOnion
TheBigOnion

Reputation: 625

How to pass and use a generic object in c#?

I have multiple methods that each return an Object.

public objA myCall(string[] args)
{           
    webAPI myAPI = new webAPI();
    returnData = myAPI.callApi("http://localhsot/api", args , "POST");

    XmlSerializer serializer = new XmlSerializer(typeof(myObj));

    using (TextReader reader = new StringReader(returnData))
    {
        objA result = (objA)serializer.Deserialize(reader);

        return result;
    }
}

And

public objB myCall(string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(myObj));

  using (TextReader reader = new StringReader(returnData))
  {
      objB result = (objB)serializer.Deserialize(reader);

      return result;
  }
}

What I would like to do is consolidate these into one method using generics. This way I can pass in the object that I would like returned. I've never used generics before and need a little help. This is what I have tried:

public T myCall<T>(ref T myObj, string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(myObj));

  using (TextReader reader = new StringReader(returnData))
  {
      myObj result = (myObj)serializer.Deserialize(reader);

      return result;
  }
}

But when I put this into Visual Studio, I get get an error saying that "myObj" is a variable but is used like a type. If you have had experience with this and are willing to help, I would appreciate it.

Upvotes: 1

Views: 164

Answers (2)

Guru Stron
Guru Stron

Reputation: 141565

You should remove from parameters myObj and change it in the body of method to T like this

public T myCall<T>(string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(T));

  using (TextReader reader = new StringReader(returnData))
  {
      T result = (T)serializer.Deserialize(reader);

      return result;
  }
}

Upvotes: 1

Igor
Igor

Reputation: 62213

You are almost there

public T myCall<T>(string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(T));

  using (TextReader reader = new StringReader(returnData))
  {
      T result = (T)serializer.Deserialize(reader);

      return result;
  }
}

And then you call it by passing the type as the generic constraint.

var result = myCall<objA>(someArguments);

On a side note (and also my opinion) objA is not a good name for a type.

Upvotes: 5

Related Questions