SlideShare a Scribd company logo
Metaprogramming in
.NET
Jason Bock
Practice Lead
ยปhttp://www.magenic.com
ยปhttp://www.jasonbock.net
ยปhttps://www.twitter.com/jasonbock
ยปhttps://www.github.com/jasonbock
ยปjasonb@magenic.com
Personal Info
https://github.com/JasonBock
Downloads
ยปDefinitions
ยปReflection
ยปSnippets
ยปExpressions
ยปModification
ยปCompilation
Overview
Rememberโ€ฆ
https://github.com/JasonBock
Definitions
http://kauilapele.files.wordpress.com/2011/11/magic.gif
Definitions
http://en.wikipedia.org/wiki/Metaprogramming
Metaprogramming:The writing of
computer programs that write or
manipulate other programs (or
themselves) as their data, or that do
part of the work at compile time that
would otherwise be done at runtime.
Definitions
http://manning.com/hazzard/
Definitions
http://manning.com/hazzard/
โ€œThe meta prefix can mean changed
or higher. It can also mean after or
beside, depending on the context. All
of those terms describe โ€ฆ various
forms of metaprogramming.โ€
Definitions
http://1.bp.blogspot.com/-MoYos-iLGR0/Tclyxk6kH6I/AAAAAAAAF08/8aX2fOxBKlo/s1600/magical-merlin-sundara-
fawn.jpg
dynamic x = Program.Create();
x.MyProperty = 42;
x.Calculate();
Definitions
http://1.bp.blogspot.com/-MoYos-iLGR0/Tclyxk6kH6I/AAAAAAAAF08/8aX2fOxBKlo/s1600/magical-merlin-sundara-
fawn.jpg
var x = 40;
eval('x = x + 2');
Definitions
http://www.wired.com/images_blogs/photos/uncategorized/2008/04/15/complexity.jpg
Definitions
http://www.machinemart.co.uk/images/library/range/large/1010.jpg
Definitions
http://www.machinemart.co.uk/images/library/range/large/1010.jpg
โ€ฆif youโ€™ve come this far, maybe youโ€™re
willing to come a little further.
Reflection
http://scarlettlibrarian.files.wordpress.com/2010/12/reflection.jpg
Reflection
[TestClass]
public class MyTests
{
[TestMethod]
public void MyTest() { }
[TestMethod]
public void AnotherTest() { }
}
Find test classes
MyTests
Find test methods
MyTest
AnotherTest
Reflection
public class AClass {}
public class AnotherClass {}
public class MyClass
{
public void MyMethod(string arg1,
Guid arg2) { ... }
}
Reflection
Assembly
TypeTypeType
MethodBase
ParameterInfoParameterInfo
Reflection
MyAssembly
AnotherClassMyClassAClass
MyMethod
arg2arg1
Reflection
var arg2Type = typeof(MyClass)
.GetMethod("MyMethod")
.GetParameters()[1].ParameterType;
Reflection
var mine = new MyClass();
var invoke = typeof(MyClass)
.GetMethod("MyMethod")
.Invoke(mine, new object[]
{ "data", Guid.NewGuid() });
Reflection
http://www.theawall.com/images/blog/time.jpg
Demo: Automatically Adding Business
Rules
Metaprogramming in .NET
Snippets
http://osx.wdfiles.com/local--files/icon:snippet/Snippet.png
Snippets
Snippets
Demo: ArgumentNullException Code
Snippet
Metaprogramming in .NET
Expressions
Expressions
Expressions
public sealed class NotNullAttribute :
InjectorAttribute<ParameterDefinition>{}
Expressions
ยปSystem.Reflection.Emit
ยปDynamicMethod
Expressions
http://www.theawall.com/images/blog/time.jpg
Expressions
public string SayHello()
{
return "Hello";
}
Expressions
.method public hidebysig instance string
SayHello() cil managed
{
.maxstack 8
ldstr "Hello"
ret
}
Expressions
.method public hidebysig instance string
SayHello() cil managed
{
.maxstack 8
ret
}
Expressions
*
3 x
/
2
+
4
f(x) = ((3 * x) / 2) + 4
Expressions
var method = new DynamicMethod("m",
typeof(double), new Type[] { typeof(double) });
var parameter = method.DefineParameter(
1, ParameterAttributes.In, "x");
var generator = method.GetILGenerator();
generator.Emit(OpCodes.Ldc_R8, 3d);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Mul);
generator.Emit(OpCodes.Ldc_R8, 2d);
generator.Emit(OpCodes.Div);
generator.Emit(OpCodes.Ldc_R8, 4d);
generator.Emit(OpCodes.Add);
generator.Emit(OpCodes.Ret);
var compiledMethod = method.CreateDelegate(
typeof(Func<double, double>)) as Func<double, double>;
Expressions
var parameter =
Expression.Parameter(typeof(double));
var method = Expression.Lambda(
Expression.Add(
Expression.Divide(
Expression.Multiply(
Expression.Constant(3d), parameter),
Expression.Constant(2d)),
Expression.Constant(4d)),
parameter).Compile() as Func<double, double>;
Expressions
var propertyName = this.GetPropertyName(
_ => _.FirstName);
// Or, in C#6...
// var propertyName =
// nameof(this.FirstName);
Demo: Evolving Code
Metaprogramming in .NET
Modification
[MaximumCalls(2)]
public void MyMethod { }
Modification
private int myMethodCalls;
[MaximumCalls(2)]
public void MyMethod
{
if(this.myMethodCalls < 2)
{
//...
this.myMethodCalls++;
}
}
Demo: Injectors
Metaprogramming in .NET
Compilation
Compilation
SyntaxTree
API
Symbol API Binding and Flow API EmitAPI
https://github.com/dotnet/roslyn
Compilation
ITest
CallMe()
var rock = new Rock<ITest>;
rock.HandleAction<int>(
_ => _.CallMe(),
() => { return 42; });
var chunk = rock.Make();
chunk.CallMe();
Rock841914
: ITest
Compilation
http://phillbarron.files.wordpress.com/2012/01/confused.jpg
Compilation
Demo: Rocks
Metaprogramming in .NET
Summary
ยปWhat didnโ€™t I cover?
โ€บ CodeDom
โ€บ T4
โ€บ Reflection.Emit
โ€บ CCI (like Cecil) (http://ccimetadata.codeplex.com/)
โ€บ dynamic, ExpandoObject
โ€บ Clay (http://clay.codeplex.com/), Gemini (http://amirrajan.net/Oak/)
Summary
http://upload.wikimedia.org/wikipedia/commons/d/de/CERO_fear.png
Summary
http://upload.wikimedia.org/wikipedia/commons/d/de/CERO_fear.png
Metaprogramming in
.NET
Jason Bock
Practice Lead
Rememberโ€ฆ
๏‚ง https://github.com/JasonBock (see notes for specific repos)
๏‚ง http://www.slideshare.net/jasonbock/metaprogramming-in-net
๏‚ง References in the notes on this slide

More Related Content

What's hot (20)

PDF
Maintainable JavaScript 2011
Nicholas Zakas
ย 
PDF
ReactJS for Programmers
David Rodenas
ย 
DOCX
My java file
Anamika Chauhan
ย 
PDF
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Anton Bangratz
ย 
KEY
Inside PyMongo - MongoNYC
Mike Dirolf
ย 
DOCX
201913046 wahyu septiansyah network programing
wahyuseptiansyah
ย 
PDF
Your code are my tests
Michelangelo van Dam
ย 
PDF
ES3-2020-07 Testing techniques
David Rodenas
ย 
PDF
TDD CrashCourse Part5: Testing Techniques
David Rodenas
ย 
PDF
2013-06-15 - Software Craftsmanship mit JavaScript
Johannes Hoppe
ย 
PDF
2013-06-24 - Software Craftsmanship with JavaScript
Johannes Hoppe
ย 
PDF
Beautiful java script
รœrgo Ringo
ย 
PPTX
PHP 5 Magic Methods
David Stockton
ย 
PPTX
Rethrowing exception- JAVA
Rajan Shah
ย 
PPTX
Shipping Pseudocode to Production VarnaLab
Dobromir Nikolov
ย 
PPTX
Java Bytecode For Discriminating Developers - GeeCON 2011
Anton Arhipov
ย 
PPTX
ATG Advanced RQL
Kate Semizhon
ย 
PPT
CLR Exception Handing And Memory Management
Shiny Zhu
ย 
PPTX
Clean Code - A&BP CC
JWORKS powered by Ordina
ย 
PDF
UA testing with Selenium and PHPUnit - PFCongres 2013
Michelangelo van Dam
ย 
Maintainable JavaScript 2011
Nicholas Zakas
ย 
ReactJS for Programmers
David Rodenas
ย 
My java file
Anamika Chauhan
ย 
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Anton Bangratz
ย 
Inside PyMongo - MongoNYC
Mike Dirolf
ย 
201913046 wahyu septiansyah network programing
wahyuseptiansyah
ย 
Your code are my tests
Michelangelo van Dam
ย 
ES3-2020-07 Testing techniques
David Rodenas
ย 
TDD CrashCourse Part5: Testing Techniques
David Rodenas
ย 
2013-06-15 - Software Craftsmanship mit JavaScript
Johannes Hoppe
ย 
2013-06-24 - Software Craftsmanship with JavaScript
Johannes Hoppe
ย 
Beautiful java script
รœrgo Ringo
ย 
PHP 5 Magic Methods
David Stockton
ย 
Rethrowing exception- JAVA
Rajan Shah
ย 
Shipping Pseudocode to Production VarnaLab
Dobromir Nikolov
ย 
Java Bytecode For Discriminating Developers - GeeCON 2011
Anton Arhipov
ย 
ATG Advanced RQL
Kate Semizhon
ย 
CLR Exception Handing And Memory Management
Shiny Zhu
ย 
Clean Code - A&BP CC
JWORKS powered by Ordina
ย 
UA testing with Selenium and PHPUnit - PFCongres 2013
Michelangelo van Dam
ย 

Similar to Metaprogramming in .NET (20)

PDF
Dynamic Binding in C# 4.0
Buu Nguyen
ย 
PPTX
Dynamic C#
Antya Dev
ย 
PPT
Understanding Reflection
Tamir Khason
ย 
PPTX
PDC Video on C# 4.0 Futures
nithinmohantk
ย 
PPTX
Dynamic Language Performance
Kevin Hazzard
ย 
PPT
Object Oriented Programming In .Net
Greg Sohl
ย 
PPTX
Overview Of .Net 4.0 Sanjay Vyas
rsnarayanan
ย 
PPTX
Framework Design Guidelines For Brussels Users Group
brada
ย 
KEY
Attributes, reflection, and dynamic programming
LearnNowOnline
ย 
PPTX
Whats New In C# 4 0 - NetPonto
Paulo Morgado
ย 
PDF
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
ย 
PPTX
Evolution of Patterns
Chris Eargle
ย 
PPTX
C#4.0 features
Yaswanth Babu Gummadivelli
ย 
PDF
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
Sean McCarthy
ย 
PPTX
Linq Introduction
Neeraj Kaushik
ย 
PPT
03 oo with-c-sharp
Naved khan
ย 
PPT
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
ย 
PPT
Metaprogramming by brandon
MaslowB
ย 
PPSX
C# - Part 1
Md. Mahedee Hasan
ย 
PDF
Expression trees in c#
Oleksii Holub
ย 
Dynamic Binding in C# 4.0
Buu Nguyen
ย 
Dynamic C#
Antya Dev
ย 
Understanding Reflection
Tamir Khason
ย 
PDC Video on C# 4.0 Futures
nithinmohantk
ย 
Dynamic Language Performance
Kevin Hazzard
ย 
Object Oriented Programming In .Net
Greg Sohl
ย 
Overview Of .Net 4.0 Sanjay Vyas
rsnarayanan
ย 
Framework Design Guidelines For Brussels Users Group
brada
ย 
Attributes, reflection, and dynamic programming
LearnNowOnline
ย 
Whats New In C# 4 0 - NetPonto
Paulo Morgado
ย 
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
ย 
Evolution of Patterns
Chris Eargle
ย 
C#4.0 features
Yaswanth Babu Gummadivelli
ย 
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
Sean McCarthy
ย 
Linq Introduction
Neeraj Kaushik
ย 
03 oo with-c-sharp
Naved khan
ย 
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
ย 
Metaprogramming by brandon
MaslowB
ย 
C# - Part 1
Md. Mahedee Hasan
ย 
Expression trees in c#
Oleksii Holub
ย 
Ad

Recently uploaded (20)

PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
PPTX
For my supp to finally picking supp that work
necas19388
ย 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
ย 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
ย 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
ย 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
PPTX
Introduction to web development | MERN Stack
JosephLiyon
ย 
PPTX
declaration of Variables and constants.pptx
meemee7378
ย 
PDF
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
ย 
PDF
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
ย 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
ย 
PPTX
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
ย 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
PDF
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
ย 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
ย 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
For my supp to finally picking supp that work
necas19388
ย 
Which Hiring Management Tools Offer the Best ROI?
HireME
ย 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
ย 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
ย 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
Introduction to web development | MERN Stack
JosephLiyon
ย 
declaration of Variables and constants.pptx
meemee7378
ย 
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
ย 
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
ย 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
ย 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
ย 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
ย 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
ย 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
Ad

Metaprogramming in .NET

Editor's Notes

  • #6: Itโ€™s all magicโ€ฆ.but not really ๏Š
  • #7: This is a pretty typical definition of metaprogramming.
  • #8: So I co-authored a bookโ€ฆ ๏Š
  • #9: This is the definition I used in my book, but what does it mean? Letโ€™s look at a couple of simple examples.
  • #10: With C# 4, you can use the dynamic keyword to manipulate members at runtime.
  • #11: In JavaScript, you can write code as a string, and have the JS environment evaluate the code for you (though eval is considered โ€˜evilโ€™)
  • #12: Metaprogramming can be viewed as taking complex code, and reducing its visibility. Thereโ€™s still complex things to be done, but metaprogramming techniques can reduce it and lead you to a design where itโ€™s relatively easy to manage
  • #13: Youโ€™re going to acquire a new set of tools. Used wisely, it can make your programming life easier.
  • #14: Doing metaprogramming in .NET requires some dedication to learn new ideas, use frameworks that may be unfamiliar, etc. However, keep at it. The further you go, the easier it becomes, and youโ€™ll start to see your programs in a whole new way.
  • #15: Reflection provides you to find out information about your code, and execute it if you want.
  • #16: A testing framework uses reflection to find all of the test classes and test methods.
  • #17: Hereโ€™s a simple piece of code, letโ€™s look at how it would be represented in a Reflection graph
  • #18: You have an assembly, types, methods, parameters, as well as events, properties, etc.
  • #19: Hereโ€™s what that code sample looks like with its names.
  • #20: If youโ€™d want to get the type of the 2nd argument, hereโ€™s the code.
  • #21: If you wanted to invoke a method on an object, hereโ€™s the code
  • #22: While Reflection is a powerful tool for metaprogramming, it can be slow. Always consider performance when using Reflection.
  • #24: You can generate code based on a template in Visual Studio. These are called Code Snippets
  • #25: Once you create the snippet, you can import it via the Code Snippets Manager
  • #26: And then use it in your code
  • #27: How do I make a code snippet for ArgumentNullException?
  • #28: Thereโ€™s a tool called ILDasm thatโ€™s been in the .NET installation since 1.0. It lets you see the guts of an assembly at its metadata levelโ€ฆ
  • #29: โ€ฆ.and at the IL level.
  • #30: With IL knowledge, you can do all sorts of tricks that C# or VB donโ€™t support. For example, you can create generic attributes that can be consumed by C# and VB.
  • #31: Knowing IL is required if you want to run new code at runtime. If you wanted to create a new type, SRE was the way to do it. If you just needed a new method, use DynamicMethod (added in 2.0)
  • #32: With SRE, you can create dynamic proxies, which are used extensively by mocking engines.
  • #33: So what the issue with IL? Itโ€™s harder to understand, and itโ€™s pretty easy to mess up. Take this simple function.
  • #34: Hereโ€™s the same function in IL.
  • #35: If the ldstr op code is gone, itโ€™ll probably compile in ilasm, but running it will create all sorts of issues (e.g. InvalidProgramException)
  • #36: Expressions allow you to view your code as a data structure โ€“ a tree. Basing an API on that can make it safer to generate code.
  • #37: Hereโ€™s what that function looks like as a dynamic method
  • #38: Hereโ€™s what it looks like using the LINQ expressions API.
  • #39: Weโ€™ve all seen the property name trick, which uses LINQ expressions. Itโ€™s a little slower, but itโ€™s โ€œsafeโ€. But thereโ€™s some really cool things you can do with expressions, like genetic programming.
  • #41: While C# doesnโ€™t support AOP out-of-box, itโ€™s possible through assembly parsing frameworks like Cecil or CCI to add aspects via the presence of attributes.
  • #42: But you need good debugging experience
  • #44: Traditionally, compilers are black boxes. You donโ€™t get access to whatโ€™s going on, and thereโ€™s lot of valuable information within.
  • #45: Roslyn opens up the compiler, providing APIs to different parts of the pipeline.
  • #46: Thereโ€™s lot of crazy things you can do if you can compile code on the fly. Letโ€™s create a dynamic class that is a mock of another class (useful for testing)
  • #47: Makes total sense, right? ๏Š
  • #48: But I can take the generated proxy class, save it to disk, and step into the code
  • #50: Knowing IL is required if you want to run new code at runtime. If you wanted to create a new type, SRE was the way to do it. If you just needed a new method, use DynamicMethod (added in 2.0)
  • #51: Donโ€™t fear metaprogramming. The tools may be a little more advanced than unusual, and you may need to invest some time, but itโ€™s worth it.
  • #52: Embrace metaprogramming. Itโ€™ll make your coding peaceful ๏Š
  • #53: GitHub repos Csla.AutoAddBusinessRules CodeSnippets ExpressionEvolver Injectors Rocks References Code Snippets (C#) - https://msdn.microsoft.com/en-us/library/f7d3wz0k(v=vs.90).aspx Creating and Using IntelliSense Code Snippets - https://msdn.microsoft.com/en-us/library/vstudio/ms165392(v=vs.100).aspx Comparison of code generation tools - http://en.wikipedia.org/wiki/Comparison_of_code_generation_tools Sigil: Adding Some (More) Magic To IL - http://kevinmontrose.com/2013/02/14/sigil-adding-some-more-magic-to-il/ Visual Studio Code Snippets - http://visualstudiocodesnippets.com/ Visual Studio code snippets - http://www.codeproject.com/Articles/737354/Visual-Studio-code-snippets