54
James Michael Hare 2012 Visual C# MVP Application Architect Scottrade August 3 rd , 2012 http://www.BlackRabbitCoder.net Twitter: @BlkRabbitCoder

C#/.NET Little Wonders

Embed Size (px)

DESCRIPTION

We've all seen the big "macro" features in .NET, this presentation is to give praise to the "Little Wonders" of .NET -- those little items in the framework that make life as a developer that much easier!

Citation preview

Page 1: C#/.NET Little Wonders

James Michael Hare2012 Visual C# MVPApplication Architect

ScottradeAugust 3rd, 2012

http://www.BlackRabbitCoder.netTwitter: @BlkRabbitCoder

Page 2: C#/.NET Little Wonders

Me:Blog: http://www.BlackRabbitCoder.netTwitter: @BlkRabbitCoder

Information on Scottrade Careers:http://jobs.scottrade.comTwitter: @scottradejobs

Page 3: C#/.NET Little Wonders

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.

Page 4: C#/.NET Little Wonders

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).

Page 5: C#/.NET Little Wonders

The Little WondersSyntactical Sugar

Implicit TypingAuto-Propertiesusing Blocksstatic Class Modifier

Castsas (TryCast)

StringCase-Insensitive Equals()static IsNullOrEmpty()static

IsNullOrWhitespace()Object:

static Equals()Path

BCL Class for Path Handling

StopwatchBCL Class for Timing

TimeSpan static Factory Methods

OperatorsConditionalNull-Coalescing

InitializersObject InitializersCollection Initializers

Extension MethodsDefining Custom

ExtensionsLINQ Extension

Methods

Page 6: C#/.NET Little Wonders

Implicit typingSo 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.

Page 7: C#/.NET Little Wonders

Auto-Implemented PropertiesMost properties simply get/set a backing

field:

Page 8: C#/.NET Little Wonders

Auto-Implemented PropertiesManually 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).

Page 9: C#/.NET Little Wonders

Auto-Implemented PropertiesC#:

Page 10: C#/.NET Little Wonders

Auto-Implemented PropertiesVB:

Page 11: C#/.NET Little Wonders

Using using BlocksWhen using an IDisposable instance, be

careful how you clean up:

What happens if exception is thrown before one or all are disposed?

Page 12: C#/.NET Little Wonders

Using using BlocksFully protecting gets ugly fast…

Page 13: C#/.NET Little Wonders

Using using Block Safer -- handles Dipose() even if exception.Can stack multiple using declarations in C#.Looks cleaner than multi-indenting.

C#:

Page 14: C#/.NET Little Wonders

Using using BlockVB doesn’t look quite as clean when

“stacked”, but still cleaner than the try/finally.VB:

Page 15: C#/.NET Little Wonders

Static Class ModifierSome utility classes contain only static

methods:

Page 16: C#/.NET Little Wonders

Static Class ModifierClasses with only static (Shared) methods

and properties shouldn’t be instantiated or inherited.

Could mark class sealed (NotInheritable) and create private constructor:

Page 17: C#/.NET Little Wonders

Static Class ModifierInstead, 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.

Page 18: C#/.NET Little Wonders

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.

Page 19: C#/.NET Little Wonders

The as Cast (TryCast)C#:

VB:

Page 20: C#/.NET Little Wonders

Case-Insensitive String EqualsSometimes 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.

Page 21: C#/.NET Little Wonders

Case-Insensitive String EqualsInstead of converting ToUpper(), use optional

argument for case-insensitivity:C#:

VB:

Can also be applied to static String.Equals().

Page 22: C#/.NET Little Wonders

String CompareReturns integer result of whether the first

argument is less, equal, or greater than the second argument.

Has optional parameter for case-insensitive.

Page 23: C#/.NET Little Wonders

Static String Empty ChecksOften 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?

Page 24: C#/.NET Little Wonders

Static String Empty ChecksThe 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.

Page 25: C#/.NET Little Wonders

Static String Empty ChecksC#:

VB:

Page 26: C#/.NET Little Wonders

Static Object Equals CheckWhat happens in the following if the LHS is

null?C#:

VB:

Equals() instance method can handle null RHS, but not LHS.

Page 27: C#/.NET Little Wonders

Static Object Equals CheckYou 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.

Page 28: C#/.NET Little Wonders

The Path ClassPath has helper methods for

parsing/combining paths.

Page 29: C#/.NET Little Wonders

The Stopwatch ClassBCL 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.

Page 30: C#/.NET Little Wonders

The Stopwatch ClassC#:

VB:

Page 31: C#/.NET Little Wonders

TimeSpan Factory MethodsHow many times have you seen code like this

and wondered what the TimeSpan represents?C#:

VB:

The constructors for TimeSpan are a bit ambiguous.

Page 32: C#/.NET Little Wonders

TimeSpan Factory MethodsTimeSpan 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.

Page 33: C#/.NET Little Wonders

TimeSpan Factory MethodsC#:

VB:

Page 34: C#/.NET Little Wonders

The Conditional OperatorEssentially 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>)

Page 35: C#/.NET Little Wonders

The Conditional OperatorC#:

VB:

Page 36: C#/.NET Little Wonders

The Null-Coalescing OperatorAllows 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 ?? substituevalue != null ? value : substitute

VB:If(value, substitue)If(value IsNot Nothing, value, substitue)

Page 37: C#/.NET Little Wonders

The Null-Coalescing OperatorC#

VB:

Page 38: C#/.NET Little Wonders

Object InitializersMany times, we create an object and then

immediately set a series of properties:

Lot of repetitive code especially if names are long:

Page 39: C#/.NET Little Wonders

Object InitializersOf 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.

Page 40: C#/.NET Little Wonders

Object InitializersC#:

VB:

Page 41: C#/.NET Little Wonders

Collection InitializersSimilarly, creating collections can be

repetitive:

Especially if the type contained is non-trivial:

Page 42: C#/.NET Little Wonders

Collection InitializersCan use collection initializer syntax to add

multiple items at time of collection construction:C#:

VB:

Page 43: C#/.NET Little Wonders

Collection InitializersEven works well in conjunction with object

initializers for initializing collections of complex objects:C#:

VB:

Page 44: C#/.NET Little Wonders

Collection InitializersWhat is the difference between these?

Page 45: C#/.NET Little Wonders

Collection InitializersInitializers 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.

Page 46: C#/.NET Little Wonders

Extension MethodsIf 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.

Page 47: C#/.NET Little Wonders

Extension MethodsC#:

Page 48: C#/.NET Little Wonders

Extension MethodsVB:

Page 49: C#/.NET Little Wonders

Extension MethodsCan 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.

Page 50: C#/.NET Little Wonders

LINQToo many times developers re-invent the

wheel.Say you have a list of Product such as:

Page 51: C#/.NET Little Wonders

LINQIf you wanted all products with value > 100

grouped by category, you could do something like…

Page 52: C#/.NET Little Wonders

LINQOr 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.

Page 53: C#/.NET Little Wonders

Questions?Questions?

Page 54: C#/.NET Little Wonders

Platinum Platinum SponsorsSponsors

Silver Silver SponsorSponsorss

Gold Gold SponsorSponsorss