Created
January 31, 2017 05:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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