The first part of this tip discussed passing anonymous type among various function calls. That would work fine in all respect as long as the function call is made within a project (single DLL). But what happens when a DLL exposes a method and returns the Anonymous Type Collection to a function defined in another DLL. (Consider an application where BusinessLayer is separated from DataLayer (separate DLLs) and the data coming from DataLayer is collection of AnonymousType) In this case it will throw a runtime exception, something like “the<anoymous property1> does not exist”. This is because the access scope of Anonymous Types is private (internal) by default, and are not accessible to the functions defined in separate DLLs. For this, there is a work around. we need to explicitly make each and every member of Anonymous Type as Public. This can be achieved by using ExpandoObject
Consider my last example GetStudentDetails(), but first, we will modify the code a little bit- instead of creating the list of objects, we will create an IEnumerable collection.
var lstDetails = from p in lstStudents
select new { p.PK_PRIMARY_KEY, NAME = p.NAME, AGE = p.AGE }; Declare the List of dynamic objects like-
List<dynamic> lstDynamicDetails = new List<dynamic>();
loop through each element and add it to the dynamic list
foreach (var item in lstDetails)
{
dynamic objDynamic = new System.Dynamic.ExpandoObject();
//with expando object you can have n numbers and any name of the properties
objDynamic.PK_PRIMARY_KEY = item.PK_PRIMARY_KEY;
objDynamic.NAME = item.NAME;
objDynamic.AGE = item.AGE;
lstDynamicDetails.Add(objDynamic);
}
Finally return the 1stDynamicDetails. This will work as similar to the method described previously, irrespective of function access scope
|
Modified code for the function GetStudentDetails() |
public List<dynamic> GetStudentDetails() { Student objStudent1 = new Student { ADMISSION_NUMBER = 01, AGE = 25, ROLL = 81, NAME = "Student Number1", PK_PRIMARY_KEY = 1 }; Student objStudent2 = new Student { ADMISSION_NUMBER = 02, AGE = 30, ROLL = 1, NAME = "Student Number2", PK_PRIMARY_KEY = 2 }; Student objStudent3 = new Student { ADMISSION_NUMBER = 03, AGE = 25, ROLL = 2, NAME = "Student Number3", PK_PRIMARY_KEY = 3 }; List<Student> lstStudents = new List<Student>(); lstStudents.Add(objStudent1); lstStudents.Add(objStudent2); lstStudents.Add(objStudent3); var lstDetails = from p in lstStudents select new { p.PK_PRIMARY_KEY, NAME = p.NAME, AGE = p.AGE }; List<dynamic> lstDynamicDetails = new List<dynamic>(); foreach (var item in lstDetails) { dynamic objDynamic = new System.Dynamic.ExpandoObject(); objDynamic.PK_PRIMARY_KEY = item.PK_PRIMARY_KEY; objDynamic.NAME = item.NAME; objDynamic.AGE = item.AGE; lstDynamicDetails.Add(objDynamic); } return lstDynamicDetails ; }