SlideShare una empresa de Scribd logo
1 de 54
James Michael Hare
                                   2012 Visual C# MVP
                                  Application Architect
                                              Scottrade
                                        August 3rd, 2012


http://www.BlackRabbitCoder.net
Twitter: @BlkRabbitCoder
Me:
  Blog: http://www.BlackRabbitCoder.net
  Twitter: @BlkRabbitCoder


Information on Scottrade Careers:
  http://jobs.scottrade.com
  Twitter: @scottradejobs
What are “Little Wonders”?
The .NET Framework is full of “macro-sized”
 goodness that can help make our coding lives easier
 by automating common tasks.
But, the .NET Framework also has a lot of smaller
 “micro-sized” tips and tricks that can improve code.
Many developers know of most of these, but it is
 often surprising how many times newer developers
 don’t.
These are just a few of those items, there are many
 more.
How do they help?
Basically, by employing these small items at the right
 time, you can increase application:
  Readability – some of the wonders make code much
   more concise and easy to read.
  Maintainability – often goes hand and hand with
   readability, by removing ambiguity of the code, it is
   easier to maintain without introducing errors.
  Performance – a few of the little wonders can even help
   increase the performance of your code (depending on
   usage).
The Little Wonders
Syntactical Sugar                Stopwatch
   Implicit Typing                  BCL Class for Timing
   Auto-Properties               TimeSpan
   using Blocks                     static Factory Methods
   static Class Modifier         Operators
Casts                               Conditional
   as (TryCast)                     Null-Coalescing
String                           Initializers
   Case-Insensitive Equals()        Object Initializers
   static IsNullOrEmpty()           Collection Initializers
   static                        Extension Methods
    IsNullOrWhitespace()             Defining Custom Extensions
Object:                             LINQ Extension Methods
   static Equals()
Path
   BCL Class for Path Handling
Implicit typing
So many times declarations and instantiations are
 redundant:
  C#:
  VB:
Since declared type is same as instantiated type, can
 use implicit typing:
  C#:
  VB:
Generally speaking, more readable since less
 redundant typing.
Auto-Implemented Properties
Most properties simply get/set a backing field:
Auto-Implemented Properties
Manually creating these can make code more bloated.
Auto-Implemented properties take the pain out of
 declaring simple properties:
  Automatically creates a private, hidden backing field.
  Automatically creates a getter that returns field.
  Automatically creates a setter that assigns field.
  VB allows you to assign auto-property inline.
  C# allows you to have different accessibility for set and
    get (i.e. you can create read-only properties).
Auto-Implemented Properties
C#:
Auto-Implemented Properties
VB:
Using using Blocks
When using an IDisposable instance, be careful how
 you clean up:




What happens if exception is thrown before one or all
 are disposed?
Using using Blocks
Fully protecting gets ugly fast…
Using using Block
Safer -- handles Dipose() even if exception.
Can stack multiple using declarations in C#.
Looks cleaner than multi-indenting.
  C#:
Using using Block
VB doesn’t look quite as clean when “stacked”, but
 still cleaner than the try/finally.
  VB:
Static Class Modifier
Some utility classes contain only static methods:
Static Class Modifier
Classes with only static (Shared) methods and
 properties shouldn’t be instantiated or inherited.
Could mark class sealed (NotInheritable) and
 create private constructor:
Static Class Modifier
Instead, mark class static and will prevent
 inheritance, instantiation, and instance members.
  C#:




  VB doesn’t have static modifier for classes:
       Modules are the VB.NET equivalent.
The as Cast (TryCast)
If you use is check followed by a cast, you are checking twice…
   C#:




    VB:




The as cast (TryCast in VB) lets you do a conditional cast if type
  is convertible, or null if not.
The as Cast (TryCast)
C#:




VB:
Case-Insensitive String Equals
Sometimes you will see someone attempting to check
 case-insensitive string equality by using ToUppper():
  C#:




  VB:


This creates a temp string that needs to be garbage
 collected later.
Case-Insensitive String Equals
Instead of converting ToUpper(), use optional
 argument for case-insensitivity:
  C#:




  VB:




Can also be applied to static String.Equals().
String Compare
Returns integer result of whether the first argument
 is less, equal, or greater than the second argument.
Has optional parameter for case-insensitive.
Static String Empty Checks
Often time in code you will see something like:
  C#:




  VB:


Compound expressions are harder to read.
Can lead to buggy code if incorrectly coded or
 inverted.
If string has whitespace, what then?
Static String Empty Checks
The System.String class has some static methods for
 checking for null, empty, or whitespace only strings:
  IsNullOrEmpty() – returns true if reference is null or
   contains a completely empty string (zero Length).
  IsNullOrWhiteSpace() – returns true if reference is
   null, zero Length, or if all characters in string are
   whitespace.
These static methods make the intent of the code
 cleaner and eliminate need for compound expression.
Inverting the condition is also much more obvious.
Static String Empty Checks
C#:




VB:
Static Object Equals Check
What happens in the following if the LHS is null?
  C#:




  VB:




Equals() instance method can handle null RHS, but
 not LHS.
Static Object Equals Check
You could check for null of LHS first, but gets ugly.
Use static (Shared) Equals() method instead:
  C#:




  VB:


Safer than using operator == for most types since ==
 relies on an operator overload to exist.
The Path Class
Path has helper methods for parsing/combining
 paths.
The Stopwatch Class
BCL class in System.Diagnostics.
Allows for much more precise timing than comparing
 DateTime instances.
Contains basic methods for controlling Stopwatch:
  Start() – marks starting time to now.
  Stop() – marks ending time to now.
  Reset() – resets start and end times.
Contains properties to query duration including:
 ElapsedMilliseconds – long for milliseconds elapsed.
 Elapsed – precicse elapsed time as a TimeSpan.
The Stopwatch Class
C#:




VB:
TimeSpan Factory Methods
How many times have you seen code like this and
 wondered what the TimeSpan represents?
  C#:




  VB:




The constructors for TimeSpan are a bit ambiguous.
TimeSpan Factory Methods
TimeSpan has a series of static factory methods:
  TimeSpan.FromDays(double days)
  TimeSpan.FromHours(double hours)
  TimeSpan.FromMinutes(double minutes)
  TimeSpan.FromSeconds(double seconds)
  TimeSpan.FromMilliseconds(double millis)
These methods can be used to create TimeSpans of
 varying durations in a way that promotes better
 readability.
TimeSpan Factory Methods
C#:




VB:
The Conditional Operator
Essentially a mini if-then-else operator.
Best used for small decisions that lead to a value
 assignment or return.
If used simply, can make code more concise.
  C#:
      <bool-expression> ? <if-true> : <if-false>
  VB:
      If(<bool-expression>, <if-true>, <if-false>)
The Conditional Operator
C#:




VB:
The Null-Coalescing Operator
Allows concise substitution for null (Nothing) references.
   C#:
       <reference> ?? <null-substitute>
    VB:
       If(<reference>, <null-substitute>)

Equivalent to conditional operator checking for null/Nothing:
   C#:
       value ?? substitue
       value != null ? value : substitute
    VB:
       If(value, substitue)
       If(value IsNot Nothing, value, substitue)
The Null-Coalescing Operator
C#




VB:
Object Initializers
Many times, we create an object and then
 immediately set a series of properties:




Lot of repetitive code especially if names are long:
Object Initializers
Of course, you could make it easier by providing
 constructors, but you lose some readability:



Also, would need several constructor overloads or
 acceptable default parameters.
Object initializers come in handy because they can be
 used to initialize any public property or field.
Improves readability since tagged with property
 name.
Object Initializers
C#:




VB:
Collection Initializers
Similarly, creating collections can be repetitive:




Especially if the type contained is non-trivial:
Collection Initializers
Can use collection initializer syntax to add multiple
 items at time of collection construction:
  C#:




  VB:
Collection Initializers
Even works well in conjunction with object
 initializers for initializing collections of complex
 objects:
  C#:




  VB:
Collection Initializers
What is the difference between these?
Collection Initializers
Initializers preserve beforefieldinit modifier in the IL:




Gives small performance bump - without beforefieldinit
  the CLR must check the class to see if static constructor
  called before accessing any static member.
Extension Methods
If you develop a good piece of generic functionality
 and want to attach it to an existing (sealed) type or
 interface, you can create an Extension Method
Treated just like a true instance method, except can
 be called off null (Nothing) reference, although this
 is not recommended.
In C#, create a static class and static method with
 this keyword marking the first argument.
In VB, create a Module and mark with
 <Extension()> attribute.
Extension Methods
C#:
Extension Methods
VB:
Extension Methods
Can call just like regular instance methods:




Can be useful for adding behavior generically or to
 interfaces.
Used to give most of the LINQ functionality to
 IEnumerable.
Overuse can cause confusion and pollute IntelliSense.
LINQ
Too many times developers re-invent the wheel.
Say you have a list of Product such as:
LINQ
If you wanted all products with value > 100 grouped
 by category, you could do something like…
LINQ
Or use the LINQ extensions methods:



Or LINQ expression syntax:



Either way, the algorithms are already written and
 unit tested and ready to use.
Don’t reinvent the wheel.
Questions?
Platinum
Sponsors



Gold
Sponsors




Silver
Sponsors

Más contenido relacionado

La actualidad más candente

Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 
Flutter session 01
Flutter session 01Flutter session 01
Flutter session 01DSC IEM
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
ParaView による可視化 Tips
ParaView による可視化 TipsParaView による可視化 Tips
ParaView による可視化 TipsFumiya Nozaki
 
Mobile development with Flutter
Mobile development with FlutterMobile development with Flutter
Mobile development with FlutterAwok
 
Motor bike by cfmesh
Motor bike by cfmeshMotor bike by cfmesh
Motor bike by cfmeshEtsuji Nomura
 
dot net technology
dot net technologydot net technology
dot net technologyImran Khan
 
Eggplant Functional - Lesson 2 (Japanese slides)
Eggplant Functional - Lesson 2 (Japanese slides)Eggplant Functional - Lesson 2 (Japanese slides)
Eggplant Functional - Lesson 2 (Japanese slides)Eggplant
 
Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...
Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...
Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...Mohamed Ansary
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Introduction to Flutter
Introduction to FlutterIntroduction to Flutter
Introduction to FlutterApoorv Pandey
 
Inside Flutter: Widgets, Elements, and RenderObjects
Inside Flutter: Widgets, Elements, and RenderObjectsInside Flutter: Widgets, Elements, and RenderObjects
Inside Flutter: Widgets, Elements, and RenderObjectsHansol Lee
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageCihad Horuzoğlu
 

La actualidad más candente (20)

DOT Net overview
DOT Net overviewDOT Net overview
DOT Net overview
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Flutter session 01
Flutter session 01Flutter session 01
Flutter session 01
 
Alice 12
Alice 12Alice 12
Alice 12
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Flutter introduction
Flutter introductionFlutter introduction
Flutter introduction
 
Flutter Festival - Intro Session
Flutter Festival - Intro SessionFlutter Festival - Intro Session
Flutter Festival - Intro Session
 
ParaView による可視化 Tips
ParaView による可視化 TipsParaView による可視化 Tips
ParaView による可視化 Tips
 
Mobile development with Flutter
Mobile development with FlutterMobile development with Flutter
Mobile development with Flutter
 
Motor bike by cfmesh
Motor bike by cfmeshMotor bike by cfmesh
Motor bike by cfmesh
 
dot net technology
dot net technologydot net technology
dot net technology
 
Eggplant Functional - Lesson 2 (Japanese slides)
Eggplant Functional - Lesson 2 (Japanese slides)Eggplant Functional - Lesson 2 (Japanese slides)
Eggplant Functional - Lesson 2 (Japanese slides)
 
Alice 11
Alice 11Alice 11
Alice 11
 
java ppt.pdf
java ppt.pdfjava ppt.pdf
java ppt.pdf
 
Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...
Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...
Translation and Commentary on Joseph Conrad's Intro of Lord Jim By Mohamed An...
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Introduction to Flutter
Introduction to FlutterIntroduction to Flutter
Introduction to Flutter
 
Inside Flutter: Widgets, Elements, and RenderObjects
Inside Flutter: Widgets, Elements, and RenderObjectsInside Flutter: Widgets, Elements, and RenderObjects
Inside Flutter: Widgets, Elements, and RenderObjects
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Destacado

Destacado (9)

More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Programming in c#
Programming in c#Programming in c#
Programming in c#
 
Java Notes
Java NotesJava Notes
Java Notes
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Core java slides
Core java slidesCore java slides
Core java slides
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Alphorm.com support de la formation programmer en C# 6
Alphorm.com support de la formation programmer en C# 6Alphorm.com support de la formation programmer en C# 6
Alphorm.com support de la formation programmer en C# 6
 

Similar a C#/.NET Little Wonders

Similar a C#/.NET Little Wonders (20)

C# features
C# featuresC# features
C# features
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd Check
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6
 
C# tutorial
C# tutorialC# tutorial
C# tutorial
 
Custom Detectors for FindBugs (London Java Community Unconference 2)
Custom Detectors for FindBugs (London Java Community Unconference 2)Custom Detectors for FindBugs (London Java Community Unconference 2)
Custom Detectors for FindBugs (London Java Community Unconference 2)
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
 
Java Basics
Java BasicsJava Basics
Java Basics
 
New features in C# 6
New features in C# 6New features in C# 6
New features in C# 6
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
C++ Training
C++ TrainingC++ Training
C++ Training
 

Último

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 

Último (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

C#/.NET Little Wonders

  • 1. James Michael Hare 2012 Visual C# MVP Application Architect Scottrade August 3rd, 2012 http://www.BlackRabbitCoder.net Twitter: @BlkRabbitCoder
  • 2. Me: Blog: http://www.BlackRabbitCoder.net Twitter: @BlkRabbitCoder Information on Scottrade Careers: http://jobs.scottrade.com Twitter: @scottradejobs
  • 3. What are “Little Wonders”? The .NET Framework is full of “macro-sized” goodness that can help make our coding lives easier by automating common tasks. But, the .NET Framework also has a lot of smaller “micro-sized” tips and tricks that can improve code. Many developers know of most of these, but it is often surprising how many times newer developers don’t. These are just a few of those items, there are many more.
  • 4. How do they help? Basically, by employing these small items at the right time, you can increase application: Readability – some of the wonders make code much more concise and easy to read. Maintainability – often goes hand and hand with readability, by removing ambiguity of the code, it is easier to maintain without introducing errors. Performance – a few of the little wonders can even help increase the performance of your code (depending on usage).
  • 5. The Little Wonders Syntactical Sugar Stopwatch  Implicit Typing  BCL Class for Timing  Auto-Properties TimeSpan  using Blocks  static Factory Methods  static Class Modifier Operators Casts  Conditional  as (TryCast)  Null-Coalescing String Initializers  Case-Insensitive Equals()  Object Initializers  static IsNullOrEmpty()  Collection Initializers  static Extension Methods IsNullOrWhitespace()  Defining Custom Extensions Object:  LINQ Extension Methods  static Equals() Path  BCL Class for Path Handling
  • 6. Implicit typing So many times declarations and instantiations are redundant: C#: VB: Since declared type is same as instantiated type, can use implicit typing: C#: VB: Generally speaking, more readable since less redundant typing.
  • 7. Auto-Implemented Properties Most properties simply get/set a backing field:
  • 8. Auto-Implemented Properties Manually creating these can make code more bloated. Auto-Implemented properties take the pain out of declaring simple properties: Automatically creates a private, hidden backing field. Automatically creates a getter that returns field. Automatically creates a setter that assigns field. VB allows you to assign auto-property inline. C# allows you to have different accessibility for set and get (i.e. you can create read-only properties).
  • 11. Using using Blocks When using an IDisposable instance, be careful how you clean up: What happens if exception is thrown before one or all are disposed?
  • 12. Using using Blocks Fully protecting gets ugly fast…
  • 13. Using using Block Safer -- handles Dipose() even if exception. Can stack multiple using declarations in C#. Looks cleaner than multi-indenting. C#:
  • 14. Using using Block VB doesn’t look quite as clean when “stacked”, but still cleaner than the try/finally. VB:
  • 15. Static Class Modifier Some utility classes contain only static methods:
  • 16. Static Class Modifier Classes with only static (Shared) methods and properties shouldn’t be instantiated or inherited. Could mark class sealed (NotInheritable) and create private constructor:
  • 17. Static Class Modifier Instead, mark class static and will prevent inheritance, instantiation, and instance members. C#: VB doesn’t have static modifier for classes:  Modules are the VB.NET equivalent.
  • 18. The as Cast (TryCast) If you use is check followed by a cast, you are checking twice…  C#:  VB: The as cast (TryCast in VB) lets you do a conditional cast if type is convertible, or null if not.
  • 19. The as Cast (TryCast) C#: VB:
  • 20. Case-Insensitive String Equals Sometimes you will see someone attempting to check case-insensitive string equality by using ToUppper(): C#: VB: This creates a temp string that needs to be garbage collected later.
  • 21. Case-Insensitive String Equals Instead of converting ToUpper(), use optional argument for case-insensitivity: C#: VB: Can also be applied to static String.Equals().
  • 22. String Compare Returns integer result of whether the first argument is less, equal, or greater than the second argument. Has optional parameter for case-insensitive.
  • 23. Static String Empty Checks Often time in code you will see something like: C#: VB: Compound expressions are harder to read. Can lead to buggy code if incorrectly coded or inverted. If string has whitespace, what then?
  • 24. Static String Empty Checks The System.String class has some static methods for checking for null, empty, or whitespace only strings: IsNullOrEmpty() – returns true if reference is null or contains a completely empty string (zero Length). IsNullOrWhiteSpace() – returns true if reference is null, zero Length, or if all characters in string are whitespace. These static methods make the intent of the code cleaner and eliminate need for compound expression. Inverting the condition is also much more obvious.
  • 25. Static String Empty Checks C#: VB:
  • 26. Static Object Equals Check What happens in the following if the LHS is null? C#: VB: Equals() instance method can handle null RHS, but not LHS.
  • 27. Static Object Equals Check You could check for null of LHS first, but gets ugly. Use static (Shared) Equals() method instead: C#: VB: Safer than using operator == for most types since == relies on an operator overload to exist.
  • 28. The Path Class Path has helper methods for parsing/combining paths.
  • 29. The Stopwatch Class BCL class in System.Diagnostics. Allows for much more precise timing than comparing DateTime instances. Contains basic methods for controlling Stopwatch: Start() – marks starting time to now. Stop() – marks ending time to now. Reset() – resets start and end times. Contains properties to query duration including: ElapsedMilliseconds – long for milliseconds elapsed. Elapsed – precicse elapsed time as a TimeSpan.
  • 31. TimeSpan Factory Methods How many times have you seen code like this and wondered what the TimeSpan represents? C#: VB: The constructors for TimeSpan are a bit ambiguous.
  • 32. TimeSpan Factory Methods TimeSpan has a series of static factory methods: TimeSpan.FromDays(double days) TimeSpan.FromHours(double hours) TimeSpan.FromMinutes(double minutes) TimeSpan.FromSeconds(double seconds) TimeSpan.FromMilliseconds(double millis) These methods can be used to create TimeSpans of varying durations in a way that promotes better readability.
  • 34. The Conditional Operator Essentially a mini if-then-else operator. Best used for small decisions that lead to a value assignment or return. If used simply, can make code more concise. C#: <bool-expression> ? <if-true> : <if-false> VB: If(<bool-expression>, <if-true>, <if-false>)
  • 36. The Null-Coalescing Operator Allows concise substitution for null (Nothing) references.  C#: <reference> ?? <null-substitute>  VB: If(<reference>, <null-substitute>) Equivalent to conditional operator checking for null/Nothing:  C#: value ?? substitue value != null ? value : substitute  VB: If(value, substitue) If(value IsNot Nothing, value, substitue)
  • 38. Object Initializers Many times, we create an object and then immediately set a series of properties: Lot of repetitive code especially if names are long:
  • 39. Object Initializers Of course, you could make it easier by providing constructors, but you lose some readability: Also, would need several constructor overloads or acceptable default parameters. Object initializers come in handy because they can be used to initialize any public property or field. Improves readability since tagged with property name.
  • 41. Collection Initializers Similarly, creating collections can be repetitive: Especially if the type contained is non-trivial:
  • 42. Collection Initializers Can use collection initializer syntax to add multiple items at time of collection construction: C#: VB:
  • 43. Collection Initializers Even works well in conjunction with object initializers for initializing collections of complex objects: C#: VB:
  • 44. Collection Initializers What is the difference between these?
  • 45. Collection Initializers Initializers preserve beforefieldinit modifier in the IL: Gives small performance bump - without beforefieldinit the CLR must check the class to see if static constructor called before accessing any static member.
  • 46. Extension Methods If you develop a good piece of generic functionality and want to attach it to an existing (sealed) type or interface, you can create an Extension Method Treated just like a true instance method, except can be called off null (Nothing) reference, although this is not recommended. In C#, create a static class and static method with this keyword marking the first argument. In VB, create a Module and mark with <Extension()> attribute.
  • 49. Extension Methods Can call just like regular instance methods: Can be useful for adding behavior generically or to interfaces. Used to give most of the LINQ functionality to IEnumerable. Overuse can cause confusion and pollute IntelliSense.
  • 50. LINQ Too many times developers re-invent the wheel. Say you have a list of Product such as:
  • 51. LINQ If you wanted all products with value > 100 grouped by category, you could do something like…
  • 52. LINQ Or use the LINQ extensions methods: Or LINQ expression syntax: Either way, the algorithms are already written and unit tested and ready to use. Don’t reinvent the wheel.