This is one of a series of posts on some of the new features in C# 6.0, which was just released.

When catching exceptions in code, you can have a different catch block for different types of exceptions:

try
{
}
catch(SqlException ex)
{
  // Do something
}
catch(Exception ex)
{
  // Log error
}

But if you want to handle exceptions differently depending on the details of the exception, you could not until now — you would have to build the logic into the block:

try
{
}
catch(SqlException ex)
{
  if(ex.Number == 2627)
  {
    // Handle primary key violation
  }
  else
  {
    // Do exactly the same thing as the main exception block
  }
}
catch(Exception ex)
{
  // Log error
}

Now, though, you can add conditions to your catch block:

try
{
}
catch(SqlException ex) when (ex.Number == 2627)
{
    // Handle primary key violation
}
catch(Exception ex)
{
  // Log error
}

Now, the first catch block will only get called if the specific error is handled. You could equally have multiple catches for the same type of exception, but with different details:

try
{
}
catch(SqlException ex) when (ex.Number == 2627)
{
    // Handle primary key violation
}
catch(SqlException ex) when (ex.Number == 2601)
{
    // Handle unique index exception
}
catch(SqlException ex)
{
   // Handle other SQL Exception
}
catch(Exception ex)
{
  // Log error
}

This not only makes code cleaner in general, it also avoids duplicate code in different blocks (duplicate code is very high up in my list of coding sins).

Note that you can also have more complex logic in the condition, and can call methods:

catch(SqlException ex) when (ex.Number == 2627 || ex.Number == 2601)

or

catch(SqlException ex) when (IsAConstraintViolation(ex.Number))

Which leads to an interesting semi-evil trick – since you can call a method, that method can do something with the exception, then return false, meaning that you are responding to the exception, but not catching it. For example, you could log the specific exception, but then let handling fall through to the next exception handler:

try
{
}
catch(SqlException ex) when (LogSqlException(ex))
{
}
catch(Exception ex)
{
  // Standard exception handling here
}

Of course, LogSqlException() would have to return false. I think that logging-type operations are the only acceptable things to handle in this way since this would otherwise generate a maintenance nightmare. I suspect, though, that we will see some interesting uses of this…

 

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

Expression bodies let you use lambda-style expression declarations for methods and properties. So, instead of:

public int Add(int x, int y) { return x + y; }
public static Rectangle CreateSquare(int left, int top, int size) 
{
  return new Rectangle(left, top, size, size);
}

public string Address
{
  get { return City + ", " + State + "  " + Zip; }
}

You can instead write:

public int Add(int x, int y) => x + y;
public static Rectangle CreateSquare(int left, int top, int size)
     => new Rectangle(left, top, size, size);

public string Address2 => City + ", " + State + "  " + Zip;

Note that, for the property, you don’t have to explicitly specify “get” since it is implied — and you can’t have a “set”.

For methods, I think that this is probably a bad idea, and I would avoid using it — you otherwise end up with two completely different formats for doing something with very little compelling advantage.

For properties, I am slightly less bothered, since it is a lot more compact (and in general I think that more compact code for simple operations is easier to read), but if the logic becomes complex (as lambdas have a habit of doing) then I would probably revert back to the more explicit format.

By the way, you can also use this syntax for indexers:

public Shape this[int index] => myList[index];

 

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

This is one of a series of posts on some of the new features in C# 6.0, which was just released. I had to be careful about naming this one because just calling it “using static” implies a different topic!

The using static is a new type of “using” statement that you can put at the top of your file declaration, but instead of referencing a namespace, you reference a specific class or enum:

using static System.Console;

This allows you to reference the static members of the class directly without including the class name:

public void SomeMethod()
{
  WriteLine("Twas Brilig");
  ReadLine("");
}

instead of

public void SomeMethod()
{
  Console.WriteLine("Twas Brillig and the slithy toves...");
  Console.ReadLine("");
}

Although, of course, you may have conflicts if you include multiple classes.

I think that this is one of those things that can be useful if used judiciously, but has the opportunity for confusion if overused.

 

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

Auto-properties were added some time ago. An auto-property lets you define a property without a backing field:

public string MyProperty {get; set;}

While these are extremely useful, if you want to initialize the properties, you generally have to do it in your constructor(s) which might be some way away from your property declaration:

public class MyClass 
{
  public MyClass()
  {
    MyProperty = "Doom";
  }

  public string MyProperty {get; set;}
}

When you have a backing field, the backing field could be initialized at the declaration:

private myField = "Doom";

Well, now you can do the same thing with auto-properties:

public string MyProperty {get; set;} = "Doom";

This keeps the value next to the property, which makes it easier to manage. You can also now create read-only properties that are initialized in the same way:

public string MyProperty {get;} = "Doom";

This isn’t that useful if you are using a constant string (since you could just as easily use a const), but if the value is initialized in a more complex way, this becomes more useful:

public string MyProperty {get;} = GetInitialValue();

Note that GetInitialValue() will have to be a static method – you can’t access instance methods because the class is not yet fully initialized.

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

Null-conditional member access is a great new feature that, I think, will help make code more bullet-proof and easier to read.

How often have you seen code like this:

MyResult mr = null;
if(ob != null)
{
  MyClass mc = ob.SomeMethod();
  if(mc != null)
  {
    MyClass2 mc2 = mc.SomeOtherMethod();
    if(mc2 != null)
      mr = mc2.SomeThirdMethod();
  }
}

or, worse:

 MyResult mr = ob.SomeMethod().SomeOtherMethod().SomeThirdMethod();

with absolutely no null checks at all. A common trick is to use the ternary operator:

MyClass mc = (ob != null) ? ob.SomeMethod() : null;
MyClass2 mc2 = (mc != null) ? mc.SomeOtherMethod() : null;
MyResult mr = (mc2 != null) ? mc2.SomeThirdMethod() : null;

which is better, but still somewhat verbose. Enter null-conditional operators:

MyResult mr = ob?.SomeMethod()?.SomeOtherMethod()?.SomeThirdMethod();

The ?. can be read as “If the thing on the left is not null, then call the thing on the right. Otherwise, just return null and stop processing.”

To be fair, I think that it is probably not a great idea to create huge chains of code using this, but used in moderation, I think that it a) makes code easier to read and b) encourages coders to actually do a null check, since it is quicker, and less verbose.

Note that this also works with indexers:

string name = myList?[1]?.Name;

This will short circuit if myList is null or if the item at position 1 in the array is null. Note, however, that if the list has less than 2 items, you will still get an exception – the code checks for nulls, not bounds.

Another cool use for the null-conditional is when dealing with events. Rather than having to check to see if the event handler is defined, you can just do this:

SomeHandler?.Invoke(this,args);

Which also has the advantage of being thread-safe. It is very common to see code like this:

if(SomeHandler != null)
  SomeHandler(this, args);

Which is fine almost all of the time — except if a different thread happens to unsubscribe to the event sometime between the check and the call. Technically, the correct code would be:

var handler = SomeHandler;
if(handler != null)
  handler(this, args);

I remember early discussions about the C# language where the discussion was whether there needed to be special handling for this to be thread-safe without the extra code. The feeling was that most of the time, this wasn’t enough of a risk to make it worth extending the language, but the null-conditional operator takes care of it now anyway.

Here are links to posts about other new features in C# 6.0:

Tagged with: ,

Visual Studio Logo

VS 2015 is now available for download from MSDN!

Probably the biggest things about this release are the new Roslyn compiler and the fact that much of .NET is now officially open source! Aside from giving the .NET team a better base for their compiler, Roslyn is extremely flexible (always good news if you are into metadata). This gives you a lot of power to build custom tools, analyzers, rewriters and other things that can let you (and vendors) improve the development experience.

One thing to note is that, unlike the old C# compiler, Roslyn is not part of a .NET install, so you can’t just assume it is present on end-user’s computers (although, of course, developers who have VS installed will have it). For people who are relying on compiler services as part of an end-user application, the old C# compiler is still present.

There is also a very exciting new version of ASP.NET/MVC coming – but that is not quite ready yet (Although a new community preview was also released today). I’ll probably do a post on this once it really comes out.

There are a fair number of improvements in .NET 4.6, including lots of speed improvements – assemblies are loaded more efficiently, there is a new 64-bit Jitter which should really help performance on 64-bit machines (which is virtually all of them now).  I’m also looking forward to playing with the released version of the .NET Native Compiler, which can create native Win32/64 apps without requiring .NET to be installed. This was originally created for improved support for the Microsoft Store, but I can see a lot of potential uses for it if it stands up to scrutiny.

This link provides a more detailed list of what’s new in .NET 4.6.

There are also some very cool new features in C# with this release. C# 6.0. I will do posts on some of my favorites, such as:

 

Tagged with: , ,

Colbert Cabinet

Someone just sent me a link to this — apparently Stephen Colbert has way too much free time before his new show starts!

This article provides a little background.

Taz 5 - SideA few weeks ago I finally purchased a 3D printer – a Lulzbot Taz 5.  In the past, I’d played with a Makerbot, and looked at a few others, but I really liked the Taz 5 – it is a bit more expensive than some of the others out there (about $2200) but is more industrial. I’ve done a few prints that have taken 20+ hours with no problems, plus it has a print size of 11.7″ x 10.8″ x 9.8″ which is huge! The Taz 5 also has a heated glass bed so you don’t have to muck about with fragile tape surfaces.

Another advantage (for me) is that Lulzbot is based in Loveland, Colorado, which is only a couple of hours drive away. Rather than ordering the Taz 5 from Amazon, I just drove up there, and got a tour of the facilities. It was very cool seeing a room full of 3D printers printing out more 3D printers (I believe they are working on Skynet next).

Lulzbot is also dedicated to Open Source, so they use Open Source software, Open Source hardware designs, etc. There is also a LulzBot Mini which is considerably cheaper.

My one complaint so far is that I wish that the Taz 5 was self-leveling like the Mini – I’ve had to tweak alignment a few times and it is a little fiddly. I think that they are planning on adding that, and I’m hoping that I will be able to upgrade.

As a software engineer, I am used to being able to make a computer do anything I like – but it is all virtual. There is something truly magical in being able to design things and have them come into existence in the real world. There are a number of different ways of creating models, but I’ve mostly been focusing on learning and using FreeCAD. This is an open source parametric CAD package. It is not entirely intuitive to use, but I went through a series of YouTube tutorials that did a good job getting me up and running.

Many people prefer to use tools like Blender to create models, and for more artistic creations, this is probably not a bad idea, but for most of the things I’ve been playing with, I like having the exact control that a CAD application provides. Other than exercises, I’ve only created a handful of things myself (which I will leave for a future post). I’ve also downloaded a few things from Thingiverse which is a fantastic resource where you can download thousands (or possibly millions) of pre-created models. By far the most useful thing I’ve downloaded so far is an EZ-Snap Razor Blade Handle which is great for separating stubborn models from the bed:

Razor HandleSo far I’ve been using Cura for my slicing and printing tool, and it does a pretty nice job. You can easily scale models and add additional models to print at the same time. I’ve mostly been staying in QuickPrint mode, but will probably start experimenting with expert mode soon. I’m hoping that it will give me more control over support structure printing (which is evil), although it sounds like I might have to look at different slicing engines if I want really fine control.

Here is a shot of the Cura interface with a fork bearing I created as one of the FreeCAD exercises:

Cura With Fork Bearing

Tagged with: , , ,

Cowthulu Site ImageIt has been about 10 years since I last seriously touched the Cowthulu web site. Originally I created the site by hand, using it as an opportunity to teach myself CSS. I also built a few utilities to synchronize menus and other items across pages.

There was also a blog, but it used a fairly primitive tool for creation (I don’t remember what it was) and the tool disappeared during one of my many system upgrades. I’ve frequently had things I wanted to blog, but it was always too much effort. The new site is in WordPress though, so if that gets too much in the way of my blogging, I’ve got bigger problems!

Time will tell how much blogging I actually do. I currently have ideas for a lot of entries, largely because they are things that I intended to blog about over the years, but never did, so I will end up doing blogs on things that happened quite some time ago as well as things moving forward.