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

R
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
1 of 21

Recommended

Road to Dynamic LINQ Part 1 by
Road to Dynamic LINQ Part 1Road to Dynamic LINQ Part 1
Road to Dynamic LINQ Part 1Axilis
597 views23 slides
Road to Dynamic LINQ - Part 2 by
 Road to Dynamic LINQ - Part 2 Road to Dynamic LINQ - Part 2
Road to Dynamic LINQ - Part 2Axilis
556 views19 slides
From DOT to Dotty by
From DOT to DottyFrom DOT to Dotty
From DOT to DottyMartin Odersky
6.8K views56 slides
C sharp by
C sharpC sharp
C sharpAhmed Vic
671 views11 slides
Preparing for Scala 3 by
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3Martin Odersky
11.1K views48 slides
Why Scala for Web 2.0? by
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?Alex Payne
24.4K views31 slides

More Related Content

What's hot

Scala by
ScalaScala
Scalaguest8996422d
8.2K views31 slides
Building Your Own DSL with Xtext by
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with XtextGlobalLogic Ukraine
2.1K views12 slides
05 functional programming by
05 functional programming05 functional programming
05 functional programmingVictor Matyushevskyy
326 views48 slides
C++vs java by
C++vs javaC++vs java
C++vs javaPradeep wolf king
2.3K views15 slides
Domain specific languages and Scala by
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and ScalaFilip Krikava
6.4K views94 slides
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос... by
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...NETFest
275 views20 slides

What's hot(18)

Domain specific languages and Scala by Filip Krikava
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and Scala
Filip Krikava6.4K views
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос... by NETFest
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
NETFest275 views
The Evolution of Scala by Martin Odersky
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
Martin Odersky44.4K views
Functional OOP, Clojure style by yoavrubin
Functional OOP, Clojure styleFunctional OOP, Clojure style
Functional OOP, Clojure style
yoavrubin3.9K views
Xtext beyond the defaults - how to tackle performance problems by Holger Schill
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
Holger Schill2.4K views
Scala - The Simple Parts, SFScala presentation by Martin Odersky
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
Martin Odersky16.5K views
Using ANTLR on real example - convert "string combined" queries into paramete... by Alexey Diyan
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 Diyan16.4K views
ANTLR4 and its testing by Knoldus Inc.
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
Knoldus Inc.3.9K views
AestasIT - Internal DSLs in Scala by Dmitry Buzdin
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
Dmitry Buzdin1K views
From delegates, to lamdas and expression trees your guide to elegant code in ... by Credera
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 ...
Credera725 views
Why Scala? by Alex Payne
Why Scala?Why Scala?
Why Scala?
Alex Payne25.6K views

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

Programming Languages: some news for the last N years by
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
1.2K views44 slides
Giving Clarity to LINQ Queries by Extending Expressions R2 by
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
221 views45 slides
Dynamic languages, for software craftmanship group by
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupReuven Lerner
524 views106 slides
Software Architecture: Principles, Patterns and Practices by
Software Architecture: Principles, Patterns and PracticesSoftware Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and PracticesGanesh Samarthyam
3.2K views131 slides
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin by
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
993 views45 slides
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z... by
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
553 views22 slides

Similar to Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees(20)

Programming Languages: some news for the last N years by Ruslan Shevchenko
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
Ruslan Shevchenko1.2K views
Giving Clarity to LINQ Queries by Extending Expressions R2 by Ed Charbeneau
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
Ed Charbeneau221 views
Dynamic languages, for software craftmanship group by Reuven Lerner
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
Reuven Lerner524 views
Software Architecture: Principles, Patterns and Practices by Ganesh Samarthyam
Software Architecture: Principles, Patterns and PracticesSoftware Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and Practices
Ganesh Samarthyam3.2K views
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin by Sencha
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
Sencha993 views
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z... by Data Con LA
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 LA553 views
JSLounge - TypeScript 소개 by Reagan Hwang
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
Reagan Hwang1.9K views
JSLab.Руслан Шевченко."JavaScript как платформа компиляции" by GeeksLab Odessa
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
JSLab.Руслан Шевченко."JavaScript как платформа компиляции"
GeeksLab Odessa476 views
Concepts of JetBrains MPS by Vaclav Pech
Concepts of JetBrains MPSConcepts of JetBrains MPS
Concepts of JetBrains MPS
Vaclav Pech2.3K views
JAZOON'13 - Paul Brauner - A backend developer meets the web: my Dart experience by jazoon13
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
jazoon1333.4K views
Python and Oracle : allies for best of data management by Laurent Leturgez
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
Laurent Leturgez192 views
Introduction to Type Script by Sam Goldman, SmartLogic by SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogic
SmartLogic1.3K views
AZMS PRESENTATION.pptx by SonuShaw16
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptx
SonuShaw164 views
Bringing your app to the web with Dart - Chris Buckett (Entity Group) by jaxLondonConference
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)
jaxLondonConference6.1K views
The openCypher Project - An Open Graph Query Language by Neo4j
The openCypher Project - An Open Graph Query LanguageThe openCypher Project - An Open Graph Query Language
The openCypher Project - An Open Graph Query Language
Neo4j2.2K views
Enhancing Domain Specific Language Implementations Through Ontology by Chunhua Liao
Enhancing Domain Specific Language Implementations Through OntologyEnhancing Domain Specific Language Implementations Through Ontology
Enhancing Domain Specific Language Implementations Through Ontology
Chunhua Liao270 views

Recently uploaded

6g - REPORT.pdf by
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdfLiveplex
10 views23 slides
Zero to Automated in Under a Year by
Zero to Automated in Under a YearZero to Automated in Under a Year
Zero to Automated in Under a YearNetwork Automation Forum
15 views23 slides
Mini-Track: AI and ML in Network Operations Applications by
Mini-Track: AI and ML in Network Operations ApplicationsMini-Track: AI and ML in Network Operations Applications
Mini-Track: AI and ML in Network Operations ApplicationsNetwork Automation Forum
10 views24 slides
Serverless computing with Google Cloud (2023-24) by
Serverless computing with Google Cloud (2023-24)Serverless computing with Google Cloud (2023-24)
Serverless computing with Google Cloud (2023-24)wesley chun
11 views33 slides
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
34 views35 slides
HTTP headers that make your website go faster - devs.gent November 2023 by
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023Thijs Feryn
22 views151 slides

Recently uploaded(20)

6g - REPORT.pdf by Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex10 views
Serverless computing with Google Cloud (2023-24) by wesley chun
Serverless computing with Google Cloud (2023-24)Serverless computing with Google Cloud (2023-24)
Serverless computing with Google Cloud (2023-24)
wesley chun11 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Powerful Google developer tools for immediate impact! (2023-24) by wesley chun
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)
wesley chun10 views
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman36 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc11 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab21 views

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