Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an anonymous type from reflection ParamInfo[]

i want to create an anonymous type inside a function, when the anonymous type properties are the function parameters.

for example, for the function: private bool CreatePerson(string FirstName, string LasName, int Age, int height);

i will have an anonymous type with the properties: FirstName,LasName,Age and height. and the values of the function parameters will be the values of the anonymous type properties.

private bool CreatePerson(string FirstName, string LasName, int Age, int height)
    {
        // Get this method parameters
        MethodBase currentMethod =  MethodBase.GetCurrentMethod();
        ParameterInfo[] parametersInfo = currentMethod.GetParameters();

        // create an object of the parameters from the function.
        foreach (ParameterInfo paramInfo in parametersInfo)
        {
            // add a property with the name of the parameter to an anonymous object and insert its value to the property.
            // WHAT DO I DO HERE?
            ....
        }

        return true;
    }
like image 815
Rodniko Avatar asked Oct 24 '10 12:10

Rodniko


1 Answers

If I understood correctly and you want to define the properties at runtime, this is not possible. Although in anonymous types you may be able to create types that you define there and then by assigning values, the name of the properties must be known at compile time.

In fact, the type is anonymous to you but not to the CLR. If you look at the assembly in ildasm.exe or reflector, you will see these anonymous types with strange names always having <> in their names.

C#'s dynamic might be able to help here but as far as I know, they help with communicating with objects that are that we do not have type information for, not creating - but there might be a way that I do not know.

like image 117
Aliostad Avatar answered Sep 16 '22 11:09

Aliostad