Object Creation using Lambda Expressions Part 2

In my previous post I talked about Lambda Expressions to create objects instead of Activator.CreateInstance.

Object Creation using Lambda Expressions Part 1

At the end of that post I said I would refactor the code into a static class with helper methods to facilitate ease of use.

In the following class there are two helper methods and three methods of creating the ObjectCreator that can then be used to create instances of an object.

Helper Methods

The two helper methods are:

  • NumberOfConstructors<T>() which returns the number of constructors that type T contains.
  • ConstructorParameters<T>() which returns an ordered Type array of the parameters that a particular constructor takes.

These methods can be used for a number of reasons, not least to validate some assumption that the calling code is making about T.

Creator Methods

Next there are three methods that can be used to create the ObjectCreator:

  • GetCreator<T>() will attempt to return an ObjectCreator for the first constructor.
  • GetCreator<T>(int constructorId) will attempt to return an ObjectCreator for the specified constructor.
  • GetCreator<T>(Type[] constructorParameters) will attempt to return an ObjectCreator for a constructor that accepts the same parameters as passed in.

Here is the class:

ObjectCreator.cs

These three methods provide multiple ways of creating an ObjectCreator depending on the circumstances of the calling code.  In the event of failure an ArgumentException will be thrown with information about the exception.

The code below illustrates some examples of using this class:

Feel free to copy the code and use as you wish but I don’t offer any guarantees.  If anyone finds any issues please let me know in the comments below.

As far as I know this will work within Unity but I don’t have a setup that enables me to test every platform.  I’d be very interested in any feedback on that issue and in particular on iOS using Unity.

 

 

 

 

One thought on “Object Creation using Lambda Expressions Part 2

  1. Pingback: Object Creation using Lambda Expressions Part 1

Leave a Reply

Your email address will not be published. Required fields are marked *