SlideShare une entreprise Scribd logo
1  sur  21
Exploring C# DSLs:
LINQ, Fluent Interfaces and
     Expression Trees
   Rasmus Kromann-Larsen
Me
• Freelance .NET Developer

• Core Group Member
  – Copenhagen .NET User Group
  – Aarhus .NET User Group


• JetBrains Academy Expert
Agenda

• Domain Specific Languages

• Static Reflection

• Code
Domain Specific Languages
• Language targeted at a specific problem

• Goals
  – Expressiveness / Productivity
  – Declarative over Imperative
  – Communication


• External vs Internal
SELECT ID, LastName
FROM Employees e
WHERE EXISTS (
    SELECT *
    FROM Orders o
    WHERE e.ID = o.EmployeeID
    AND OrderDate = '9/5/11')
(?:(?:rn)?[ t])*(?:(?:(?:[^()<>@,;:".[] 000-
031]+(?:(?:(?:rn)?[ t]
)+|Z|(?=[["()<>@,;:".[]]))|"(?:[^"r]|.|(?:(?:rn)?[
t]))*"(?:(?: rn)?[ t])*)(?:.(?:(?:rn)?[
t])*(?:[^()<>@,;:".[] 000-031]+(?:(?:(
?:rn)?[t])+|Z|(?=[["()<>@,;:".[]]))|"(?:[^"r]|.|(?
:(?:rn)?[ t]))*"(?:(?:rn)?[ t])*))*@(?:(?:rn)?[
t])*(?:[^()<>@,;:".[] 000-


... snip ...

"()<>@,;:".[]]))|"(?:[^"r]|.|(?:(?:rn)?[
t]))*"(?:(?:rn)?[ t]) *))*@(?:(?:rn)?[
t])*(?:[^()<>@,;:".[] 000-031]+(?:(?:(?:rn)?[ t])
+|Z|(?=[["()<>@,;:".[]]))|[([^[]r]|.)*](?:(?:rn)
?[ t])*)(?: .(?:(?:rn)?[ t])*(?:[^()<>@,;:".[] 000-
031]+(?:(?:(?:rn)?[ t])+|Z
|(?=[["()<>@,;:".[]]))|[([^[]r]|.)*](?:(?:rn)?[
t])*))*>(?:( ?:rn)?[ t])*))*)?;s*)
Talk Focus

• Internal C# DSLs
  – Less ramp-up
  – Automatic tooling support
  – Emergent in many new libraries


• Developer benefits > non-dev communication
[Subject("Making a customer preferred")]
public class when_a_regular_customer_is_made_preferred
{
    static Customer _customer;

    Establish context = () =>
        _customer = new Customer();

    Because of = () =>
        _customer.MakePreferred();

    It should_mark_the_customer_as_preferred = () =>
        _customer.IsPreferred.ShouldBeTrue();
}
people.Where(x => x.Age < 50)



     from x in people
     where x.Age < 50
     select x
LINQ
• Most(?) successful C# DSL

• Depending on C# 3.0 features
  – Anonymous Types
  – Extension Methods
  – Expression Trees


• Great DSL building blocks
LINQ

people.Where(x => x.Age < 50)



     from x in people
     where x.Age < 50
     select x
Expression Trees
Expression Trees
• Extracting AST-like structure from lambda
  expressions

• Expression<TDelegate>
Static Reflection

• Statically typed reference to code element
• No magic strings
• Tool support / Refactorability



• typeof(Person).GetProperty(”Name”);
 vs
• GetProperty<Person>(x => x.Name);
GetProperty<Person>(x => x.Name)
GetPropertyName
public string GetPropertyName(Expression body)
{
    // Unwrap boxing
    if (body is UnaryExpression)
    {
        body = ((UnaryExpression) body).Operand;
    }

    var memberExpression = body as MemberExpression;

    if (memberExpression == null)
    {
        throw new Exception("Descriptive exception message.");
    }

    return memberExpression.Member.Name;
}
GetProperty<Person>(x => x.Friend.Name)
Object Printing
Recap

• We use DSLs almost every day

• Expression Trees are not (that) dangerous

• It doesn’t have to be hard to write a DSL!
More Information?

• Domain Specific Languages by Martin Fowler

• Open Source Projects
  – Fubu
  – Most IoC containers
  – AutoMapper
  – AutoFixture
  – Fluent Nhibernate
  ... and many more.
Questions?


 Rasmus Kromann-Larsen

       @rasmuskl
rasmus@kromann-larsen.dk
    www.rasmuskl.dk

Contenu connexe

Tendances

Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with XtextGlobalLogic Ukraine
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and ScalaFilip Krikava
 
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...NETFest
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Functional OOP, Clojure style
Functional OOP, Clojure styleFunctional OOP, Clojure style
Functional OOP, Clojure styleyoavrubin
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problemsHolger Schill
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Alexey Diyan
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testingKnoldus Inc.
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaDmitry Buzdin
 
From delegates, to lamdas and expression trees your guide to elegant code in ...
From delegates, to lamdas and expression trees your guide to elegant code in ...From delegates, to lamdas and expression trees your guide to elegant code in ...
From delegates, to lamdas and expression trees your guide to elegant code in ...Credera
 

Tendances (18)

Scala
ScalaScala
Scala
 
Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with Xtext
 
05 functional programming
05 functional programming05 functional programming
05 functional programming
 
C++vs java
C++vs javaC++vs java
C++vs java
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and Scala
 
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Functional OOP, Clojure style
Functional OOP, Clojure styleFunctional OOP, Clojure style
Functional OOP, Clojure style
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problems
 
DSL explained _
DSL explained _DSL explained _
DSL explained _
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
 
From delegates, to lamdas and expression trees your guide to elegant code in ...
From delegates, to lamdas and expression trees your guide to elegant code in ...From delegates, to lamdas and expression trees your guide to elegant code in ...
From delegates, to lamdas and expression trees your guide to elegant code in ...
 
Scalax
ScalaxScalax
Scalax
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

Similaire à Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees

Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N yearsRuslan Shevchenko
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Ed Charbeneau
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupReuven Lerner
 
Software Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and PracticesSoftware Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and PracticesGanesh Samarthyam
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSencha
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Data Con LA
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개Reagan Hwang
 
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"GeeksLab Odessa
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platformRuslan Shevchenko
 
Concepts of JetBrains MPS
Concepts of JetBrains MPSConcepts of JetBrains MPS
Concepts of JetBrains MPSVaclav Pech
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#Remik Koczapski
 
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experienceJAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experiencejazoon13
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementLaurent Leturgez
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicSmartLogic
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxSonuShaw16
 
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)jaxLondonConference
 
The openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query LanguageThe openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query LanguageNeo4j
 
Enhancing Domain Specific Language Implementations Through Ontology
Enhancing Domain Specific Language Implementations Through OntologyEnhancing Domain Specific Language Implementations Through Ontology
Enhancing Domain Specific Language Implementations Through OntologyChunhua Liao
 

Similaire à Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees (20)

Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
 
Software Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and PracticesSoftware Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and Practices
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
 
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platform
 
Concepts of JetBrains MPS
Concepts of JetBrains MPSConcepts of JetBrains MPS
Concepts of JetBrains MPS
 
Oracle by Muhammad Iqbal
Oracle by Muhammad IqbalOracle by Muhammad Iqbal
Oracle by Muhammad Iqbal
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
 
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experienceJAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogic
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptx
 
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
The openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query LanguageThe openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query Language
 
Enhancing Domain Specific Language Implementations Through Ontology
Enhancing Domain Specific Language Implementations Through OntologyEnhancing Domain Specific Language Implementations Through Ontology
Enhancing Domain Specific Language Implementations Through Ontology
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees

  • 1. Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees Rasmus Kromann-Larsen
  • 2. Me • Freelance .NET Developer • Core Group Member – Copenhagen .NET User Group – Aarhus .NET User Group • JetBrains Academy Expert
  • 3. Agenda • Domain Specific Languages • Static Reflection • Code
  • 4. Domain Specific Languages • Language targeted at a specific problem • Goals – Expressiveness / Productivity – Declarative over Imperative – Communication • External vs Internal
  • 5. SELECT ID, LastName FROM Employees e WHERE EXISTS ( SELECT * FROM Orders o WHERE e.ID = o.EmployeeID AND OrderDate = '9/5/11')
  • 6. (?:(?:rn)?[ t])*(?:(?:(?:[^()<>@,;:".[] 000- 031]+(?:(?:(?:rn)?[ t] )+|Z|(?=[["()<>@,;:".[]]))|"(?:[^"r]|.|(?:(?:rn)?[ t]))*"(?:(?: rn)?[ t])*)(?:.(?:(?:rn)?[ t])*(?:[^()<>@,;:".[] 000-031]+(?:(?:( ?:rn)?[t])+|Z|(?=[["()<>@,;:".[]]))|"(?:[^"r]|.|(? :(?:rn)?[ t]))*"(?:(?:rn)?[ t])*))*@(?:(?:rn)?[ t])*(?:[^()<>@,;:".[] 000- ... snip ... "()<>@,;:".[]]))|"(?:[^"r]|.|(?:(?:rn)?[ t]))*"(?:(?:rn)?[ t]) *))*@(?:(?:rn)?[ t])*(?:[^()<>@,;:".[] 000-031]+(?:(?:(?:rn)?[ t]) +|Z|(?=[["()<>@,;:".[]]))|[([^[]r]|.)*](?:(?:rn) ?[ t])*)(?: .(?:(?:rn)?[ t])*(?:[^()<>@,;:".[] 000- 031]+(?:(?:(?:rn)?[ t])+|Z |(?=[["()<>@,;:".[]]))|[([^[]r]|.)*](?:(?:rn)?[ t])*))*>(?:( ?:rn)?[ t])*))*)?;s*)
  • 7. Talk Focus • Internal C# DSLs – Less ramp-up – Automatic tooling support – Emergent in many new libraries • Developer benefits > non-dev communication
  • 8. [Subject("Making a customer preferred")] public class when_a_regular_customer_is_made_preferred { static Customer _customer; Establish context = () => _customer = new Customer(); Because of = () => _customer.MakePreferred(); It should_mark_the_customer_as_preferred = () => _customer.IsPreferred.ShouldBeTrue(); }
  • 9. people.Where(x => x.Age < 50) from x in people where x.Age < 50 select x
  • 10. LINQ • Most(?) successful C# DSL • Depending on C# 3.0 features – Anonymous Types – Extension Methods – Expression Trees • Great DSL building blocks
  • 11. LINQ people.Where(x => x.Age < 50) from x in people where x.Age < 50 select x
  • 13. Expression Trees • Extracting AST-like structure from lambda expressions • Expression<TDelegate>
  • 14. Static Reflection • Statically typed reference to code element • No magic strings • Tool support / Refactorability • typeof(Person).GetProperty(”Name”); vs • GetProperty<Person>(x => x.Name);
  • 16. GetPropertyName public string GetPropertyName(Expression body) { // Unwrap boxing if (body is UnaryExpression) { body = ((UnaryExpression) body).Operand; } var memberExpression = body as MemberExpression; if (memberExpression == null) { throw new Exception("Descriptive exception message."); } return memberExpression.Member.Name; }
  • 19. Recap • We use DSLs almost every day • Expression Trees are not (that) dangerous • It doesn’t have to be hard to write a DSL!
  • 20. More Information? • Domain Specific Languages by Martin Fowler • Open Source Projects – Fubu – Most IoC containers – AutoMapper – AutoFixture – Fluent Nhibernate ... and many more.
  • 21. Questions? Rasmus Kromann-Larsen @rasmuskl rasmus@kromann-larsen.dk www.rasmuskl.dk