Ropstah
Ropstah

Reputation: 17804

How to instantiate object from string using Linq New method and provide a constructor parameter?

How can I provide a constructor parameter when instantiating an object from string using Linq New method?

I do the following to instantiate the object without parameters, however I would like to provide one for my DefaultWebRazorHostFactory which requires a constructor parameter. Is this possible?

Dim factoryType As Type = TypeFactory(typeName)
Dim o as Func(Of WebRazorHostFactory) = Expression.Lambda(Of Func(Of WebRazorHostFactory))(Expression.[New](factoryType)).Compile()

Upvotes: 1

Views: 204

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063774

Using a c# example:

Type type = typeof(SqlConnection);
var param = Expression.Parameter(typeof(string));

var body = Expression.New(type.GetConstructor(new Type[] {typeof(string)}),param);
var func = Expression.Lambda<Func<string, SqlConnection>>(body, param).Compile();

Upvotes: 2

Related Questions