Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

pass data type into function

I have the following two functions, their only difference is the type that it returns. is there any simple way to combine these two functions into a single function and pass the data type as a parameter?

        public List<CCG_OrderData> getCCG_ItemData(string url)
        {
            string jsonData = AddBracketsToJsonString(getJsonData(url));
            return JsonConvert.DeserializeObject<List<CCG_OrderData>>(jsonData);
        }

        public List<CCG_ReceivedOrders> getCCG_ItemData2(string url)
        {
            string jsonData = AddBracketsToJsonString(getJsonData(url));
            return JsonConvert.DeserializeObject<List<CCG_ReceivedOrders>>(jsonData);
        }

Open in new window

0
Big Monty
Asked:
Big Monty
1 Solution
 
käµfm³d 👽Commented:
You can make a generic method:

public List<T> getCCG_ItemData<T>(string url)
{
    string jsonData = AddBracketsToJsonString(getJsonData(url));
    return JsonConvert.DeserializeObject<List<T>>(jsonData);
}

Open in new window


Then it's simply a matter of calling the method with the correct type argument:

CCG_OrderData a = getCCG_ItemData<CCG_OrderData>("www.example.com");
CCG_ReceivedOrders b = getCCG_ItemData<CCG_ReceivedOrders>("www.example.com");

Open in new window

0
 
AndyAinscowCommented:
If both CCG_OrderData and CCG_ReceivedOrders had a common class they inherit from then you could use casting BUT the generic method suggested by kaufmed above is neater.

ps.  If you look closely you will see JsonConvert.DeserializeObject that you use is using the same, generic, technique.
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Author Commented:
perfect, just what I was looking for
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now