SlideShare a Scribd company logo
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
Implicit Typing
Auto-Properties
using Blocks
static Class Modifier
Casts
as (TryCast)
String
Case-Insensitive Equals()
static IsNullOrEmpty()
static
IsNullOrWhitespace()
Object:
static Equals()
Path
BCL Class for Path Handling
Stopwatch
BCL Class for Timing
TimeSpan
static Factory Methods
Operators
Conditional
Null-Coalescing
Initializers
Object Initializers
Collection Initializers
Extension Methods
Defining Custom Extensions
LINQ Extension Methods
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?Questions?

More Related Content

What's hot

The "Evils" of Optimization
The "Evils" of OptimizationThe "Evils" of Optimization
The "Evils" of Optimization
BlackRabbitCoder
 
Effective Java
Effective JavaEffective Java
Effective Java
Brice Argenson
 
C#
C#C#
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The Lambda
Togakangaroo
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
Mahmoud Abdallah
 
Essential language features
Essential language featuresEssential language features
ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caring
sporst
 
Packer Genetics: The selfish code
Packer Genetics: The selfish codePacker Genetics: The selfish code
Packer Genetics: The selfish code
jduart
 
C# in depth
C# in depthC# in depth
C# in depth
Arnon Axelrod
 
How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.
PVS-Studio
 
How to make fewer errors at the stage of code writing. Part N1
How to make fewer errors at the stage of code writing. Part N1How to make fewer errors at the stage of code writing. Part N1
How to make fewer errors at the stage of code writing. Part N1
Andrey Karpov
 
Cs30 New
Cs30 NewCs30 New
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
Nico Ludwig
 
Tutorial c#
Tutorial c#Tutorial c#
Tutorial c#
Mohammad Faizan
 
Assignment1 B 0
Assignment1 B 0Assignment1 B 0
Assignment1 B 0
Mahmoud
 
Difference between java and c#
Difference between java and c#Difference between java and c#
Difference between java and c#
TECOS
 
Introduction to mobile reversing
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversing
jduart
 
Grounded Pointers
Grounded PointersGrounded Pointers
Grounded Pointers
Andrey Karpov
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
Jack Nutting
 

What's hot (19)

The "Evils" of Optimization
The "Evils" of OptimizationThe "Evils" of Optimization
The "Evils" of Optimization
 
Effective Java
Effective JavaEffective Java
Effective Java
 
C#
C#C#
C#
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The Lambda
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
 
Essential language features
Essential language featuresEssential language features
Essential language features
 
ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caring
 
Packer Genetics: The selfish code
Packer Genetics: The selfish codePacker Genetics: The selfish code
Packer Genetics: The selfish code
 
C# in depth
C# in depthC# in depth
C# in depth
 
How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.
 
How to make fewer errors at the stage of code writing. Part N1
How to make fewer errors at the stage of code writing. Part N1How to make fewer errors at the stage of code writing. Part N1
How to make fewer errors at the stage of code writing. Part N1
 
Cs30 New
Cs30 NewCs30 New
Cs30 New
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
 
Tutorial c#
Tutorial c#Tutorial c#
Tutorial c#
 
Assignment1 B 0
Assignment1 B 0Assignment1 B 0
Assignment1 B 0
 
Difference between java and c#
Difference between java and c#Difference between java and c#
Difference between java and c#
 
Introduction to mobile reversing
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversing
 
Grounded Pointers
Grounded PointersGrounded Pointers
Grounded Pointers
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 

Viewers also liked

Summer Training Report
Summer Training ReportSummer Training Report
Summer Training Report
Savigya Singh
 
Summer Internship Report Presentation
Summer Internship Report PresentationSummer Internship Report Presentation
Summer Internship Report Presentation
Savigya Singh
 
6 Weeks Project Based Summer Training
6 Weeks Project Based Summer Training6 Weeks Project Based Summer Training
6 Weeks Project Based Summer Training
Tech Mentro
 
Summer Training In Java
Summer Training In JavaSummer Training In Java
Summer Training In Java
DUCC Systems
 
Industrial Training report on java
Industrial  Training report on javaIndustrial  Training report on java
Industrial Training report on java
Softvision Info Solutions Private Limited
 
Smart tv
Smart tvSmart tv
iPhone 6
iPhone 6iPhone 6
Revealing C# 5
Revealing C# 5Revealing C# 5
Revealing C# 5
Praveen Prajapati
 
Three innovative C# features
Three innovative C# featuresThree innovative C# features
Three innovative C# features
Vostrikov Arkady
 
Using advanced C# features in Sharepoint development
Using advanced C# features in Sharepoint developmentUsing advanced C# features in Sharepoint development
Using advanced C# features in Sharepoint development
sadomovalex
 
The battle of browsers
The battle of browsersThe battle of browsers
The battle of browsers
Vostrikov Arkady
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
Zeeshan Ahmad
 
C# 6 Features
C# 6 FeaturesC# 6 Features
C# 6 Features
NoelMc Grath
 
New features in C# 6
New features in C# 6New features in C# 6
New features in C# 6
Software Associates
 
Summer Engineering Internship Training Report, ADRDE Agra, DRDO
Summer Engineering Internship Training Report, ADRDE Agra, DRDOSummer Engineering Internship Training Report, ADRDE Agra, DRDO
Summer Engineering Internship Training Report, ADRDE Agra, DRDO
Aayush Singhal
 
Oops pramming with examples
Oops pramming with examplesOops pramming with examples
Oops pramming with examples
Syed Khaleel
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
techfreak
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
Swarup Kumar Boro
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
Nguyen Patrick
 
04 iec t1_s1_oo_ps_session_05
04 iec t1_s1_oo_ps_session_0504 iec t1_s1_oo_ps_session_05
04 iec t1_s1_oo_ps_session_05
Niit Care
 

Viewers also liked (20)

Summer Training Report
Summer Training ReportSummer Training Report
Summer Training Report
 
Summer Internship Report Presentation
Summer Internship Report PresentationSummer Internship Report Presentation
Summer Internship Report Presentation
 
6 Weeks Project Based Summer Training
6 Weeks Project Based Summer Training6 Weeks Project Based Summer Training
6 Weeks Project Based Summer Training
 
Summer Training In Java
Summer Training In JavaSummer Training In Java
Summer Training In Java
 
Industrial Training report on java
Industrial  Training report on javaIndustrial  Training report on java
Industrial Training report on java
 
Smart tv
Smart tvSmart tv
Smart tv
 
iPhone 6
iPhone 6iPhone 6
iPhone 6
 
Revealing C# 5
Revealing C# 5Revealing C# 5
Revealing C# 5
 
Three innovative C# features
Three innovative C# featuresThree innovative C# features
Three innovative C# features
 
Using advanced C# features in Sharepoint development
Using advanced C# features in Sharepoint developmentUsing advanced C# features in Sharepoint development
Using advanced C# features in Sharepoint development
 
The battle of browsers
The battle of browsersThe battle of browsers
The battle of browsers
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
 
C# 6 Features
C# 6 FeaturesC# 6 Features
C# 6 Features
 
New features in C# 6
New features in C# 6New features in C# 6
New features in C# 6
 
Summer Engineering Internship Training Report, ADRDE Agra, DRDO
Summer Engineering Internship Training Report, ADRDE Agra, DRDOSummer Engineering Internship Training Report, ADRDE Agra, DRDO
Summer Engineering Internship Training Report, ADRDE Agra, DRDO
 
Oops pramming with examples
Oops pramming with examplesOops pramming with examples
Oops pramming with examples
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
 
04 iec t1_s1_oo_ps_session_05
04 iec t1_s1_oo_ps_session_0504 iec t1_s1_oo_ps_session_05
04 iec t1_s1_oo_ps_session_05
 

Similar to C# features

C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
BlackRabbitCoder
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
kavinilavuG
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
nicolbiden
 
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
PVS-Studio
 
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
Andrey Karpov
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
LenchoMamudeBaro
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
Nimrita Koul
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
Sandeep Chawla
 
Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio
Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-StudioAnalysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio
Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio
PVS-Studio
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
Akhil Mittal
 
C# interview
C# interviewC# interview
C# interview
ajeesharakkal
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
Mihai Todor
 
Java performance
Java performanceJava performance
Java performance
Rajesuwer P. Singaravelu
 
C Sharp Developer Roadmap By Scholarhat PDF
C Sharp Developer Roadmap By Scholarhat PDFC Sharp Developer Roadmap By Scholarhat PDF
C Sharp Developer Roadmap By Scholarhat PDF
Scholarhat
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++
PVS-Studio
 
C# tutorial
C# tutorialC# tutorial
C# tutorial
sarangowtham_gunnam
 
C++ Training
C++ TrainingC++ Training
C++ Training
SubhendraBasu5
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 

Similar to C# features (20)

C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
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
 
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
 
Java Basics
Java BasicsJava Basics
Java Basics
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio
Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-StudioAnalysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio
Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
 
C# interview
C# interviewC# interview
C# interview
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
Java performance
Java performanceJava performance
Java performance
 
C Sharp Developer Roadmap By Scholarhat PDF
C Sharp Developer Roadmap By Scholarhat PDFC Sharp Developer Roadmap By Scholarhat PDF
C Sharp Developer Roadmap By Scholarhat PDF
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++
 
C# tutorial
C# tutorialC# tutorial
C# tutorial
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 

More from sagaroceanic11

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reportssagaroceanic11
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensicssagaroceanic11
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimes
sagaroceanic11
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attacks
sagaroceanic11
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attacks
sagaroceanic11
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidence
sagaroceanic11
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computers
sagaroceanic11
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays world
sagaroceanic11
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mware
sagaroceanic11
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overview
sagaroceanic11
 
Virtualisation basics
Virtualisation basicsVirtualisation basics
Virtualisation basics
sagaroceanic11
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisation
sagaroceanic11
 
6 service operation
6 service operation6 service operation
6 service operation
sagaroceanic11
 
5 service transition
5 service transition5 service transition
5 service transition
sagaroceanic11
 
4 service design
4 service design4 service design
4 service design
sagaroceanic11
 
3 service strategy
3 service strategy3 service strategy
3 service strategy
sagaroceanic11
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecycle
sagaroceanic11
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3
sagaroceanic11
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
sagaroceanic11
 
Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
sagaroceanic11
 

More from sagaroceanic11 (20)

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reports
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensics
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimes
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attacks
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attacks
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidence
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computers
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays world
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mware
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overview
 
Virtualisation basics
Virtualisation basicsVirtualisation basics
Virtualisation basics
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisation
 
6 service operation
6 service operation6 service operation
6 service operation
 
5 service transition
5 service transition5 service transition
5 service transition
 
4 service design
4 service design4 service design
4 service design
 
3 service strategy
3 service strategy3 service strategy
3 service strategy
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecycle
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
 
Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
 

Recently uploaded

[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdfLee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
leebarnesutopia
 
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's TipsGetting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
ScyllaDB
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
UiPathCommunity
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
"What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w..."What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w...
Fwdays
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
FilipTomaszewski5
 
Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!
Ortus Solutions, Corp
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 

Recently uploaded (20)

[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdfLee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
 
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's TipsGetting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
Getting the Most Out of ScyllaDB Monitoring: ShareChat's Tips
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
"What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w..."What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w...
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
 
Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 

C# features

  • 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 Implicit Typing Auto-Properties using Blocks static Class Modifier Casts as (TryCast) String Case-Insensitive Equals() static IsNullOrEmpty() static IsNullOrWhitespace() Object: static Equals() Path BCL Class for Path Handling Stopwatch BCL Class for Timing TimeSpan static Factory Methods Operators Conditional Null-Coalescing Initializers Object Initializers Collection Initializers Extension Methods Defining Custom Extensions LINQ Extension Methods
  • 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.