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

PPTX
Code Reactions - An Introduction to Reactive Extensions
PPTX
Extending C# with Roslyn and Code Aware Libraries
PPTX
Unit testing CourseSites Apache Filter
PDF
Java Bytecode for Discriminating Developers - JavaZone 2011
PDF
Redux for ReactJS Programmers
PDF
JS and patterns
PDF
ES3-2020-06 Test Driven Development (TDD)
ODP
Introduccion a Jasmin
Code Reactions - An Introduction to Reactive Extensions
Extending C# with Roslyn and Code Aware Libraries
Unit testing CourseSites Apache Filter
Java Bytecode for Discriminating Developers - JavaZone 2011
Redux for ReactJS Programmers
JS and patterns
ES3-2020-06 Test Driven Development (TDD)
Introduccion a Jasmin

What's hot (20)

PDF
Maintainable JavaScript 2011
PDF
ReactJS for Programmers
DOCX
My java file
PDF
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
KEY
Inside PyMongo - MongoNYC
DOCX
201913046 wahyu septiansyah network programing
PDF
Your code are my tests
PDF
ES3-2020-07 Testing techniques
PDF
TDD CrashCourse Part5: Testing Techniques
PDF
2013-06-15 - Software Craftsmanship mit JavaScript
PDF
2013-06-24 - Software Craftsmanship with JavaScript
PDF
Beautiful java script
PPTX
PHP 5 Magic Methods
PPTX
Rethrowing exception- JAVA
PPTX
Shipping Pseudocode to Production VarnaLab
PPTX
Java Bytecode For Discriminating Developers - GeeCON 2011
PPTX
ATG Advanced RQL
PPT
CLR Exception Handing And Memory Management
PPTX
Clean Code - A&BP CC
PDF
UA testing with Selenium and PHPUnit - PFCongres 2013
Maintainable JavaScript 2011
ReactJS for Programmers
My java file
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Inside PyMongo - MongoNYC
201913046 wahyu septiansyah network programing
Your code are my tests
ES3-2020-07 Testing techniques
TDD CrashCourse Part5: Testing Techniques
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
Beautiful java script
PHP 5 Magic Methods
Rethrowing exception- JAVA
Shipping Pseudocode to Production VarnaLab
Java Bytecode For Discriminating Developers - GeeCON 2011
ATG Advanced RQL
CLR Exception Handing And Memory Management
Clean Code - A&BP CC
UA testing with Selenium and PHPUnit - PFCongres 2013
Ad

Similar to Metaprogramming in .NET (20)

PDF
Dynamic Binding in C# 4.0
PPTX
Dynamic C#
PPT
Understanding Reflection
PPTX
PDC Video on C# 4.0 Futures
PPTX
Dynamic Language Performance
PPT
Object Oriented Programming In .Net
PPTX
Overview Of .Net 4.0 Sanjay Vyas
PPTX
Framework Design Guidelines For Brussels Users Group
 
KEY
Attributes, reflection, and dynamic programming
PPTX
Whats New In C# 4 0 - NetPonto
PDF
Building DSLs On CLR and DLR (Microsoft.NET)
PPTX
Evolution of Patterns
PPTX
C#4.0 features
PDF
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
PPTX
Linq Introduction
PPT
03 oo with-c-sharp
PPT
Lo Mejor Del Pdc2008 El Futrode C#
PPT
Metaprogramming by brandon
PPSX
C# - Part 1
PDF
Expression trees in c#
Dynamic Binding in C# 4.0
Dynamic C#
Understanding Reflection
PDC Video on C# 4.0 Futures
Dynamic Language Performance
Object Oriented Programming In .Net
Overview Of .Net 4.0 Sanjay Vyas
Framework Design Guidelines For Brussels Users Group
 
Attributes, reflection, and dynamic programming
Whats New In C# 4 0 - NetPonto
Building DSLs On CLR and DLR (Microsoft.NET)
Evolution of Patterns
C#4.0 features
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
Linq Introduction
03 oo with-c-sharp
Lo Mejor Del Pdc2008 El Futrode C#
Metaprogramming by brandon
C# - Part 1
Expression trees in c#
Ad

Recently uploaded (20)

PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
System and Network Administration Chapter 2
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Digital Systems & Binary Numbers (comprehensive )
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
ai tools demonstartion for schools and inter college
PPTX
Transform Your Business with a Software ERP System
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Digital Strategies for Manufacturing Companies
PDF
top salesforce developer skills in 2025.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPT
Introduction Database Management System for Course Database
Wondershare Filmora 15 Crack With Activation Key [2025
PTS Company Brochure 2025 (1).pdf.......
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
How to Choose the Right IT Partner for Your Business in Malaysia
System and Network Administration Chapter 2
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Digital Systems & Binary Numbers (comprehensive )
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
ai tools demonstartion for schools and inter college
Transform Your Business with a Software ERP System
Upgrade and Innovation Strategies for SAP ERP Customers
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Digital Strategies for Manufacturing Companies
top salesforce developer skills in 2025.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Introduction Database Management System for Course Database

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