4

I am building a asp.net web api 2 service. I need to create multiple endpoints. The service only returns data. I have around 200 end points & every end point return different type of data. I do not want to create multiple models representing each type. So instead I have decided to return dynamic type as the return type of end point.

[Route("abc/xyz")]
        public dynamic GetData()
        {
            List<dynamic> dataList = new List<dynamic>();
            dynamic data = new ExpandoObject();
            data.category = "Cat 1";
            data.value = 210.0;
            data.color = "#023867";
            dataList.Add(data);

            data = new ExpandoObject();
            data.category = "Cat 2";
            data.value = 110.23;
            data.color = "#4094d0";
            dataList.Add(data);

            data = new ExpandoObject();
            data.category = "Cat 3";
            data.value = 195.56;
            data.color = "#0b4e95";
            dataList.Add(data);


            return dataList;
        }

While this works fine, I have read this is not a good approach. I just want to know what can be disadvantages of this approach?

SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • 2
    Well for starters you lose type safety. In your example there, nothing stops the 3 items in your list from having different "shapes" which could lead to accidental bugs. – dmeglio Jan 26 '16 at 19:49
  • @dman2306. agreed. But that risk is associated with `dynamic` type. I wanted to know in terms of scalability, performance, serialization etc – SharpCoder Jan 26 '16 at 19:52
  • +1 @dman2306. @SharpCoder for performance point `ExpandoObject` is `IDictionary`. So serialization cost is same as serializing a List of key value store. – vendettamit Jan 26 '16 at 20:12
  • good read: http://stackoverflow.com/questions/7478387/how-does-having-a-dynamic-variable-affect-performance – user2404597 Jan 26 '16 at 20:14
  • No not many disadvantages. Can't actually think of any. On the contrary u can use the absence of type checking to your advantage. – Preet Singh Jan 27 '16 at 12:09

0 Answers0