LINQed IN

Blog by Troy Magennis on Software Architecture, Development and Management

About the author

Troy Magennis is a software developer living in Seattle, WA. Troy is a Microsoft MVP, the author of many articles, and the founder of HookedOnLINQ.com, a LINQ specific wiki reference site.
E-mail me Send mail

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

DfM for Software (Part 1) - Design for Manufacturing 101

In electronics design, many elements can directly impact the cost of manufacturing a product. DfM aimed to move the tradeoff analysis for decisions affecting manufacturing as early as possible in a design phase. I'll attempt to move this into the software architecture realm in a future article, but for now I want to explain how this worked in Electronic Product design.

What design decision matter in Electronics?

In electronic product design, here are a few to start your thought process -

Component Selection - Choosing components from an approved supplier and components that meet requirements but don't exceed specification (giving latitude to safety margins) directly impact cost of an item. Assisting engineers choose preferred part, parts already purchased and in inventory, and offering alternatives can really decrease costs and improve turnaround time.

Printed Circuit Board Size and Shape - Small PCB's aren't made one at a time. They are panelized onto larger sheets, fabricated and even assembled (components positioned and soldered into place) in that form before being broken apart and put into their cases. The more individual boards you can fit to a panel, the less waste and fewer panels need to be moved through auto-assembly equipment.

Printed Circuit Board Technology - If you make the board smaller to fit a certain device, you often need to add 'layers' for interconnecting components. This adds cost; If you make individual features smaller to fit more interconnects onto fewer layers, the manufacturing yield decreases due to mis-registrations. Its a real trade-off and highly dependent on your partners capabilities.

Printed Circuit Board Hole Count and Sizes - For some PCB technologies, drilling holes can be time consuming. Smaller holes needs to be positioned more accurately and these drill bits break more often. Normally, fewer holes of larger sizes is the cheapest way to go; However, some PCB technologies don't incur a cost per hole - which one will you specify?

Component Placement - Where is it safe to put large components? Where will the battery connect? Where are the pushbuttons? All of these decisions need to be considered when the PCB is being designed - BUT they seriously impact the final case design. How can the electronics designers and the mechanical (and brand) designers collaborate to agree on an acceptable design? For extremely high volume designs, placing similar components in the same orientation can reduce the number of machine rotations and component reel changes which reduces the total time of assembly. Saving 1 minute for 1 million pieces is substantial!

Early Focus and Scoring Matrix Definition

Design for Manufacture initiatives aimed to bring focus on the types of decisions made above and allow engineers and designers to perform trade-off analysis as early as possible in the process. The product might have to be smaller than a competitors and that forces a smaller PCB size and shape, which then causes a specific choice of technology - However, the key aim was to understand that early and make informed choices about which remaining options fulfill the global good.

To build a Report Card or Scoring Matrix, the basic process is -

  1. Get together with all of your partners, suppliers, fabricators and designers and brainstorm a set of issues that impact cost. Similar to the list provided above, the idea is to get the 'issues list' on the table.
  2. Group these issues into a sub-set that can actually be measured and scored. E.g. "Number of boards per panel", "Number of holes smaller than 0.5mm", "Number of different components types", etc.
  3. Determine relative weighting for each measurement. Some requirements cannot be broken, other just incur a cost. I'll propose a process for determining this weighting in a future article; for now, just understand they won't all have the same weighting factor.
  4. Build the scoring scale for each factor. This step tries to normalize the different scales of measurements into a smaller linear set (i.e. 1 to 5, rather than 1 to 1 million for one factor, and 1 to 10 for another)
  5. Calibrate the scorecard by testing on existing systems. Agree and alter the specific factor "Weightings" until you gain confidence in the scorecard
  6. Use the scorecard on future design discussions.

Summary

Is it just as simple as substituting "IT Operations" for "Fabricators"; "Usability/Interactive Designers" for "Packaging Designers"; "External Hosting Partners" for "Suppliers"? 

In future articles i'll look deeper into -

  • How to build a weighted score card based on issues relevant to software
  • Propose some software specific issues and attempt to weight those appropriately
  • Test our new scorecard and determine if it is achieving the goal we intended.

Be interested in comments as to whether other people agree there might by parity between DfM in Electronics to DfM in Software.

Troy.


Posted by t_magennis on Monday, June 23, 2008 8:18 AM
Permalink | Comments (25) | Post RSSRSS comment feed

Can Design for Manufacture Principles Reduce Software Development and Operational Costs?

I started out in the electronics engineering field, and moved into the software side of electronics design automation business shortly after that. Back in the early 1990's a lot of effort was being put into Design for Manufacturing. This was in the recognition that very small decisions made early by an isolated engineer, could have massive consequences down the road impacting costs. There were a few leaders and advocates in the field, mainly from HP and IBM at the time.

One incident recalled by Happy Holder, a HP engineer at that time was the reduction in cost of the HP Laserjet III printers. By altering the size of the main printed circuit board size by a few inches one way, they were able to double the production yield of that assembly, halving the raw material cost of the PCB. Happy Holden and IBM's Tucker Garrison at the time came up with a few simple methods for evaluating designs and allocating a report card. The most complex part of the process was getting the right people in the room to agree on the right criteria to measure, and to weight those measurements in the right way.

Manufacturing optimization comes down to improving production yield (reducing waste) and speeding up the process (reducing touch time); These principles are well known to all those proponents of Lean Manufacturing and Theory of Constraints. This book is a good start - Agile Management for Software Engineering: Applying the Theory of Constraints for Business Results (The Coad Series).

Is software yield (throughput) equivalent to DFM for Electronics "Speeding up the process"? The aforementioned books clearly describes the process of improving throughput by reducing the waste and understanding the current blocking issues. But I cannot find a process that brings focus of the cost of decisions back to the earliest possible decision point, when it is relatively simple to move many directions.

It seems obvious there is room for innovation here. Provide a framework (what DFM calls report cards) that developers and architects can use to assess possible solutions and designs for a requirement. I plan over the next few weeks to explain how the Electronics DFM process worked, and suggest a few techniques that might improve our up-front decision making process.

Troy.


Posted by t_magennis on Sunday, June 22, 2008 9:07 AM
Permalink | Comments (0) | Post RSSRSS comment feed

New Blog

Due to the amount of spam I was getting (300 odd comments a day) on Community Server - I've decided to move to a simpler blogging engine in the hope I can keep current with new versions, being .NET Blog Engine. Unfortunately, my version of Community Server was so old that I was unable to successfully export the previous posts. I'll move them manually, but it means that this won't happen overnight!

Anyway, bear with me. I promise to restore order as quickly as I can.

Troy.

 


Posted by t_magennis on Thursday, June 19, 2008 2:55 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Go Green - Server Virtualization

The company I work hosts a decent size data center to support its business (a website hitting around 1.5Mil hits a day, and countless business applications to keep the company in business). Around the end of last year our backup-power (UPS') and air-conditioning were hitting the alarming 90% level (this is understated!).

The issue wasn't the number of production servers, but rather the pre-production servers for Development, Testing and Staging. Replicating the rather large interconnected complex environment took hundreds of servers, all at 5% CPU utilization most times during the month!

Our Savior: Server virtualization

Just by converting as many pre-production servers to virtual instances and hosting these on decent machines, we saw a reduction to below 45% capacity. The additional benefit is that many of these machines were hosted on poor, unstable hardware previously - virtualized, these are running on solid hardware and in many cases perform better than they did.

If every company house that has software development and testing server resources virtualized their pre-production environments imagine how much less power our server rooms would consume. That has got to be better for the financial operating cost and also better for the environment in general!

Troy.


Categories: Software Business
Posted by t_magennis on Friday, June 13, 2008 4:12 AM
Permalink | Comments (1) | Post RSSRSS comment feed

LINQ to SQL - Stored Procedure Signature Change Impacts

Consider the scenario: V1.0 is the current application which needs to continue to run without change, and V2.0 is the new application which will alter the existing stored procedure that both V1.0 and V2.0 will be using when released. Both applications use LINQ to SQL to access the stored procedure code.

What Stored Procedure signature changes will cause V1.0 to fail?

Add Parameter – Optional  (OK)

Non-breaking change for V1.0. Since this parameter is not passed in from V1.0, the stored procedure will use the default specified in the stored procedure parameter declaration.

Add Parameter – Mandatory (Breaking)

Breaking change for V1.0 with an exception message “'stored procedure name' expects parameter '@param', which was not supplied.” The workaround is to make this parameter optional by adding a default value to the parameter declaration.

Delete Parameter – Optional (Mostly breaking)

Breaking change for V1.0, except in the case where a Stored Procedure definition for LINQ to SQL has been manually coded to exclude the parameter being deleted (in the V1.0 codebase). In general, all parameters are declared in the LINQ to SQL C#, or VB code to call a Stored Procedure. However, it is possible to declare your own method definition that chooses to exclude one or more optional parameters.

Delete Parameter – Mandatory (Breaking)

Breaking change for V1.0. No workaround. The parameter can be ignored in the new implementation of the stored procedure, but the declaration needs to remain in place until all versions who pass that parameter are deprecated.

Increase Parameter Size/Scale (OK)

Non-breaking change for V1.0. If V1.0 encountered errors due to the parameter size being too small, these will be corrected by increasing the parameter size.

Decrease Parameter Size/Scale (Mostly OK)

The parameter data is truncated if it exceeds the size of a declared parameter. This will not cause an error during Stored Procedure execution, but it might cause a functional error in the application. A change of this type should be carefully analyzed.

Add Default to Existing Parameter (OK)

Non-breaking change for V1.0.

Remove Default from Existing Parameter (Mostly OK)

Non-Breaking change for V1.0, except in the case where a manual Stored Procedure declaration has been made omitting an optional parameter. All LINQ to SQL definitions for the Stored Procedure and callers should be examined to ensure they pass the parameter dropping the default.

Reorder Parameters (OK)

Non-breaking change for V1.0. Parameters are accessed via their names. However, other applications might set parameters by index position, and these will fail.

Rename Parameter (Breaking)

Breaking change for V1.0. A renamed parameter is seen as a deletion of the current parameter and the addition of a new parameter.

Troy.


Categories: LINQ
Posted by t_magennis on Saturday, May 24, 2008 4:09 AM
Permalink | Comments (0) | Post RSSRSS comment feed

.NET 3.5 Enhancements Training Kit

A comprehensive set of hands on labs and training material has been release for a number of .NET 3.5 Enhancements by the Visual Studio & .NET Framework evangelism team. Nice work guys.

"The .NET Framework 3.5 Enhancements Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the .NET 3.5 Enhancement features including:

  • ASP.NET MVC,
  • ASP.NET Dynamic Data,
  • ASP.NET AJAX History,
  • ASP.NET Silverlight controls,
  • ADO.NET Data Services
  • ADO.NET Entity Framework."

You can download it from here.

Troy.


Categories: Resources
Posted by t_magennis on Thursday, April 17, 2008 4:32 AM
Permalink | Comments (2) | Post RSSRSS comment feed

Tips for WinForms Memory and Painting Debugging

Every now and then I come across a Windows Forms application that has memory leak, or graphic resource leak issues. In managed environments like .NET, some developers overlook that many components wrap un-managed finite resources.  I worked with a fellow developer Mike Zhang today, and because of the difficulties in replicating the issue, we decided that a full pass through the entire source code fixing these issues was our best shot at solving a niggling production issue. After today, here are our top 4 tips and the first steps to ensuring you have a well behaved Windows Forms .NET application.

Begin Update / End Update (Blank, unpainted regions of the screen)

Many Windows controls have a BeginUpdate and EndUpdate methods. These inhibit any Paint events being called when a lot of data is being added to a ListView for example. Big trouble occurs if an EndUpdate isn’t called matching a BeginUpdate! Most general case, is an exception occurs after the begin, but before the EndUpdate gets called.

To Fix: Do a solution wide search for “BeginUpdate”; Go through the result list (yes, EVERY one of them) and ensure that a the EndUpdate is wrapped in a Finally block.

BAD

   1:  this.BeginUpdate();
   2:  // lots of work, including work that may throw an exception!
   3:  // ...
   4:  this.EndUpdate();

GOOD

   1:  this.BeginUpdate();
   2:  try
   3:  {
   4:       // lots of work, including work that may throw an exception!
   5:  }
   6:  finally
   7:  {
   8:      // EndUpdate called even in the case of an Exception in the lots of work above.
   9:      this.EndUpdate();
  10:  }

Pen, Brush and Graphic Resources (Resource leak)

Even in .NET, a lot of managed code uses unmanaged resources. These managed wrappers implement the IDisposible pattern, where the Dispose method nicely releases all unmanaged resources. However – What if Dispose doesn’t get called? Either because Garbage Collection in .NET is happens on its own non-deterministic timetable, some external reference keeps an object alive, or an exception occurs and Dispose is never called. This manifests itself as areas that don’t draw properly or have an enclosed red cross.

To Fix: Do a solution wide search for “Graphic ”, “Pen “ and “Brush “; Go through the result list (yes, EVERY one of them) and ensure that the scope of the Brush, Pen or Graphic is within a using clause, or a try/finally block.

Read: "using" statement reference on MSDN: http://msdn2.microsoft.com/en-us/library/yh598w02.aspx

BAD

   1:      Graphics g = Graphics.FromImage(sourceImage);
   2:      Pen pen = new Pen();
   3:      // lots of work, including work that might fail
   4:      g.DrawRectangle(pen, 10, 10, 100, 100);
   5:      throw new Exception();
   6:      pen.Dispose(); // never called
   7:      g.Dispose(); // never called

GOOD

   1:      using(Graphics g = Graphics.FromImage(sourceImage))
   2:      {
   3:          using(Pen pen = new Pen())
   4:          {
   5:              // lots of work, including work that might fail
   6:              g.DrawRectangle(pen, 10, 10, 100, 100);
   7:              throw new Exception();
   8:           } // calls pen.Dispose() in all cases
   9:      } // calls g.Dispose() in ALL cases

Manual Event Wiring Up and Object Lifetime (memory and resource leak)

This is without a doubt the most common (and some say only common) memory leak on .NET applications. If your component subscribes to an event in ANOTHER component or class, you must –

a) Unhook yourself in your Dispose method for the form or class you subscribed FROM

b) Avoid multiple hookups to an event if your form is opened, or called multiple times

Tips:

a) Hookup events using the Forms designer when possible; This automatically handles events in the proper way

b) To be sure multiple hookups don’t accidently occur, remove yourself from an event before hooking your event up (this is safe, even the first time) –

BAD
ValidationGlobalManager.OnValidate += new My ValidationHandler(MyValidationFunction);


GOOD
  ValidationGlobalManager.OnValidate -= new My ValidationHandler(MyValidationFunction);
  ValidationGlobalManager.OnValidate += new My ValidationHandler(MyValidationFunction);

c) If you hook up an event outside of InitializeComponent (i.e. NOT through the forms designer), then YOU are responsible for unhooking your event in the Dispose() method of your form.

OnPaint and OnDraw Event Handlers - Call the base. implementation in all cases (unpredictable drawing behavior)

Many controls allow you to implement your own OnDraw and OnPaint event handlers. However, the base.OnDraw(); or base.OnPaint(); methods MUST be called under all conditions, even in the case your code fails with an exception.

To Fix: Do a solution wide search for “OnDraw ” and “OnPaint“; Go through the result list (yes, EVERY one of them) and ensure that

a) the base call is first, so it always runs, OR

b) the base call is protected with a try/finally block

Mike and Troy.


Tags: ,
Categories: C#
Posted by t_magennis on Wednesday, April 09, 2008 4:23 AM
Permalink | Comments (0) | Post RSSRSS comment feed

AForge - Image, Math, Vision, Neuro and Computer Learning Libraries

I'm probably the last to know, but I had a real need for some solid imaging and graphic library source code. I was incredibly impressed with the AForge library by Andrew Kirillov.

Get the source and library here: AForge on code.google.com

AForge.NET is a C# framework designed for developers and researchers in the fields of Computer Vision and Artificial Intelligence - image processing, neural networks, genetic algorithms, machine learning, etc.

At this point the framework is comprised of 5 main and some additional libraries:

  • AForge.Imaging – a library for image processing routines and filers;
  • AForge.Neuro – neural networks computation library;
  • AForge.Genetic – evolution programming library;
  • AForge.Vision – computer vision library;
  • AForge.Machine Learning – machine learning library.

Releases are frequent; The code clearly written; Good samples - all round a great project. Nice work to all those involved.

Troy.


Tags: ,
Categories: C#
Posted by t_magennis on Wednesday, April 09, 2008 4:18 AM
Permalink | Comments (0) | Post RSSRSS comment feed

LINQ Reference Mug and Mousemat

I put together a mug and mouse-mat design with LINQ Reference information. I wanted to have a list of the standard query operators and the new C# Query Expression Syntax on hand at all times. My only concern is spilling coffee over the keyboard when looking up the "Join" syntax reference!

combo_mug_front combo_mug_back sqo_mousepad

They take information from the HookedOnLINQ Wiki website, and you can buy them for $14.99 if you think they might be useful.

Buy a LINQ SQO and Query Expression for $14.99 + shipping

Buy a LINQ SQO Mousemat for $14.99

I don't have a VB equivalent yet, and I'd be interested if anyone has ideas for improving them or can point out errors or omissions.

Troy.


Tags: ,
Categories: C# | LINQ | HookedOnLINQ
Posted by t_magennis on Friday, February 08, 2008 4:35 AM
Permalink | Comments (0) | Post RSSRSS comment feed

CodeCamp 2008 Seattle Notes

I was fortunate enough to attend Code Camp in Seattle last weekend. It was great to see the event attended by around 300 keen developers.

I took notes throughout some sessions, and posted full details the HookedOnLINQ.com website.

By far, the Parallel LINQ session was a standout. I was surprised just how cleanly the ParallelFx team have committed to making multiple processor development mainstream. This is a library and feature set that is important to watch.

Troy.


Tags:
Categories: C# | LINQ | Resources
Posted by t_magennis on Thursday, January 31, 2008 4:42 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Prioritizing and Assigning Scale to Feature Lists and Bugs Efficiently

Sorting, prioritizing or ordering features and business objectives (or tasks, or bugs, etc) with a large group of stakeholders can be painful. Often the loudest voice in the room gets there way; some people just sit in the corner too scared to raise their objections. After sitting through many of these, I thought I’d post some ideas for improving the experience, accuracy and interaction –
  1. Do a quick read through of all the items to set the room to a common definition and understanding of the terms and items being discussed
  2. Clearly post the definition of each scale on a poster/whiteboard in clear view. If you are the moderator stand near it to re-affirm the definitions during discussion
  3. People can assign the boundary conditions quicker than the middle territory. Often a quick pass through the list solely to assign the top rating or the bottom rating (in, out, will, won’t, etc). This process also warms the group up and gets the blood flowing. It is important that if there is ANY dissent, that item be skipped
  4. The moderator should keep an eye on if someone isn’t contributing and focus a question for opinion in that person’s direction when the domain would suit (especially if it is an “obvious” yes or no). This is also a way of making sure a dominant personality gets slowed down in driving an agenda
  5. People get better at the process through experience. At regular intervals, revisit a subset and ascertain the group still feels the same way
  6.  After each break (at least every 1 hour), re-evaluate the last few items to “re-synch” people’s barometer. Depending on the time of day or the day of the week (or the amount of caffeine here in Seattle) – people can change their votes

The prioritization process is absolutely central to any agile process. Making sure you get accurately reflected priorities with large group can be very challenging.

Troy.


Posted by t_magennis on Wednesday, January 16, 2008 4:50 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Lean Architecture - How much up-front architecture is needed in a Agile project?

How much up-front design or architecture to do in an agile project is always a contentious issue. Having the job title with "Architect" in it makes me personally biased; Having a background as a developer and product manager in successful agile XP gives me a huge respect for agile development practices and somewhat balances my development approach. This posting tries to define my current view on how to balance good up-front architectural planning (minimal, but where it counts) and how to assess whether more or less architectural oversight needs to be applied during a project through intervention.

Many agile scenarios promote that a project be split in a set of features; These features prioritized into milestones by the "Customer" and then these features be worked in in almost a serialized fashion. The focus is on completing the current feature, whilst promoting that refactoring be the tool of choice when a later feature adds or alters a previously signed-off complete and closed item.

I can see some issues with this when followed blindly. My definition of "Refactoring" centers on improving currently functional code with lessons that emerge throughout a project. What I see in many projects is that "Refactoring" is the title given to an almost rewriting of a previously closed feature because the number and scope of changes to keep it operating in the face of the new feature. This is bad, and it is seriously affecting development velocity.

Here is my proposed compromise, that allows features to be built in (semi)-ignorance of future features, whilst still allowing for intervention if a pattern of serious re-writing (or refactoring if you want to water the terminology  down) begins to affect velocity -

  • Up-front architecture that should always be carried out as iteration 0 of any project includes anything that WILL BE NEEDED for EVERY feature (or requirements that will cause a registration of almost every feature that has already been completed). This includes technology choices, communication and integration patterns, operational requirements like logging, deployment strategy and localization requirements can be used as a starting list.
  • At regular intervals (e.g. 1/4, 1/3, 1/2, 2/3, 3/4) of the way through features in a project analyze the task breakdowns of the latter features to determine if there is a class of task that might be eliminated by an architectural building block or by more holistic design/planning

It is the second bullet point I want to discuss further in this posting.

My boss David Anderson run a pretty tight Lean Software software development department. A lot of the lean principles are facilitated by using a Kanban tracking system (and its electronic counterpart being the data captured in Microsoft TFS). The data captured is very thorough and used as a management tool in determining progress, bottlenecks and general project health. My goal is to use the feature and tasks completed so far to assist in determining where architectural intervention or more up-front planning could avoid that class of task being necessary in future work.

Lets look at an example - In a current project that is very integration heavy with a large ERP/CRM system, that our lack of solid planning for the interface specifications (which weren't ready when we started, but are available now) is cause way too much rework as we move through the features in a linear fashion. It way pay dividends in team velocity to introduce a feature right now that looks at the spectrum of interface specifications we now have and strawman the entire message / web service interfaces. If this reduces the number of tasks in future feature that would have revisited completed interfaces and added that extra field, or changed that database schema - improved velocity is inevitable.

But there is a balance - striving for perfection in this planning intervention would also be catastrophic to feature completion velocity. Going overboard with architecture is just as evil as sticking ones head in the sand and simply working longer hours or hiring more developers to close the backlog gap.

Be interested if other teams have analyzed task types to look for patterns or work that might be eliminated by a targeted architectural focus.

Troy.


Posted by t_magennis on Sunday, January 13, 2008 4:52 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Does Continuous Integration Scale to Enterprise Projects?

I've often heard and seen large teams struggle when implementing some agile project practices in large enterprises. I recently joined Corbis who were using many agile practices (introduced by my boss, David Anderson who wrote Agile Management book), but Continuous Integration and Automated Builds weren't on the list.

We discussed why CI was needed for a while, and then successfully implemented it. During this process, I kept careful notes on the barriers we encountered and how those barriers were overcome. On David's urging (I mentioned he was by boss right and does my reviews), I put together this draft article (Continuous Integration at Enterprise Scale.pdf (681.47 kb)). I'm keen to hear feeback on it.

Here is the Introduction -

Introduction

Continuous Integration and an Automated Build process are common practices employed by many high-functioning agile software teams. Many small teams are reporting high productivity improvements, but success stories of Continuous Integration and Automated Builds for Enterprise Scale software projects are much rarer. Some agile pundits have stated that there is a scale limitation for agile practices and these practices are in-appropriate for Enterprise Scale (or high staff count) projects.

This article aims to explore if and why the measurable benefits of Continuous Integration and Automated Build processes begin to decline as application size, and team size grows.

Our conclusion is that there is no inherent reason why Continuous Integration and Automate Build processes won’t scale to any size team. In fact, this article concludes that the problems these techniques solve are a higher pain point for Enterprise Scale applications and become more essential than ever. In addition, this article provides guidance on how to scale agile practices and how to make smart architectural choices up-front to ensure smooth adoption of Continuous Integration and Automated Builds leading to smoother projects and improved success rates.

Interested in your thoughts....

Troy.

Continuous Integration at Enterprise Scale.pdf (681.47 kb)


Posted by t_magennis on Monday, November 26, 2007 4:55 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Null Coalescing Operator

This came up today in the office, so I thought i'd post a reminder of a useful operator in C# that first appeared in C# 2.0.

When Nullable Types were introduced, Microsoft also added an operator to make dealing with null values easier. This avoids a lot of if/else checking for null values.

The normal form is:  [variable] ?? [value if variable is null]

A simple example is when dealing with nullable types, like nullable int values -

int? i = null;
int? j = 42;

int result1 = i ?? 0; // result1 is 0
int result2 = j ?? 0; // result2 is 42

The results are: result1 = 0 (because i was null), and result2 = 42 (because j had a value).

The null coalescing operator removes a lot of the clutter of testing a variable for null and assigning a default value. This is often necessary when casting a nullable type back to its non-nullable counterpart.

To read more see lots of references on this Google  search.

Troy.


Tags:
Categories: C#
Posted by t_magennis on Tuesday, November 20, 2007 5:05 AM
Permalink | Comments (0) | Post RSSRSS comment feed

The Null Coalescing Operator - ??

This came up today in the office, so I thought i'd post a reminder of a useful operator in C# that first appeared in C# 2.0.

When Nullable Types were introduced, Microsoft also added an operator to make dealing with null values easier. This avoids a lot of if/else checking for null values.

The normal form is:  [variable] ?? [value if variable is null]

A simple example is when dealing with nullable types, like nullable int values -

int? i = null;
int? j = 42;

int result1 = i ?? 0; // result1 is 0
int result2 = j ?? 0; // result2 is 42

The results are: result1 = 0 (because i was null), and result2 = 42 (because j had a value).

The null coalescing operator removes a lot of the clutter of testing a variable for null and assigning a default value. This is often necessary when casting a nullable type back to its non-nullable counterpart.

To read more see lots of references on this Google  search.

Troy.


Tags:
Categories: C#
Posted by t_magennis on Tuesday, November 20, 2007 5:04 AM
Permalink | Comments (0) | Post RSSRSS comment feed