Skip to content

Instantly share code, notes, and snippets.

@d-saravanan
Created January 31, 2017 05:25
Show Gist options
  • Save d-saravanan/c3f34fcc975bb419ea23c2881b61f196 to your computer and use it in GitHub Desktop.
Save d-saravanan/c3f34fcc975bb419ea23c2881b61f196 to your computer and use it in GitHub Desktop.
How to create types using Lambda Expressions as against using System.Reflection in .Net
using System;
using System.Linq.Expressions;
namespace ConsoleTester
{
interface Ix
{
string Email { get; set; }
string Name { get; set; }
}
class x : Ix
{
public string Name { get; set; }
public string Email { get; set; }
}
class Program
{
static T Instantiate<T>(Type refType)
{
var expr = Expression.New(refType.GetConstructor(Type.EmptyTypes));
var xi = LambdaExpression.Lambda(expr).Compile().DynamicInvoke();
return (T)xi;
}
static void Main(string[] args)
{
var a = Instantiate<x>(typeof(x));
a.Email = "[email protected]";
a.Name = "company";
Console.WriteLine(a.Email);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment