James Michael Hare

...hare-brained ideas from the realm of software development...
posts - 134 , comments - 1033 , trackbacks - 0

My Links

News

Welcome to my blog! I'm a Sr. Software Development Engineer in Seattle, WA. I've been doing C++/C#/Java development for over 18 years, but have definitely learned that there is always more to learn!

All thoughts and opinions expressed in my blog and my comments are my own and do not represent the thoughts of my employer.

Blogs I Read

MCC Logo MVP Logo

Follow BlkRabbitCoder on Twitter

Tag Cloud

Archives

Post Categories

Thursday, May 2, 2013

C#/.NET Fundamentals: Three Tech.Pro Tutorials

I know I’ve been a bit quiet on my blog lately.  I’ve still been adjusting to my new life in Seattle and learning different technologies for my new job.  It’s been a lot of fun, but has left me with precious little free time!

That said, a few months ago I was invited to throw together some tutorials on Tech.Pro as part of their startup series, so I decided to give it a go.  Their site has a nice collection of tutorials of various skill level ratings from several different authors. 

These were the tutorials I threw together…

 

The Dos and Don’ts of Extension Methods

A look at the “rules-of-thumb” that I’ve come up with through the years to provide simple guidelines for good extension method style.

 

The joy of Tuples and Anonymous Types

A look at anonymous types and tuples and how they can be leveraged to create quick instances of simple types and when it is appropriate to use them.

 

Demystifying LINQ

A basic tutorial on what LINQ is and the basics behind how it works.

 

Anyway, peruse them if you like and see how you like them.  I hope to be able to write another post here on my blog soon! 

 

Posted On Thursday, May 2, 2013 9:09 PM | Comments (0) |

Friday, March 8, 2013

C#/.NET Little Wonders: Extension Methods Demystified

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

I have had the pleasure to program in a variety of programming languages throughout the years including the trifecta of C++, Java, and C#. It's often interesting how these three languages are so similar and yet have such key differences as well. Each of them has features that I miss when I work with the others. But, if I had to pick one standout feature that I love in C# (and long for when working with the other languages) it would be LINQ.

There is a wealth of algorithmic and framework components in LINQ that make development more rapid and code easier to maintain.  Extension methods, are a ubiquitous feature of LINQ even if you don't know you are using them. And even without using LINQ, they are a very interesting feature of .NET in of itself and worth a more detailed discussion.

Extension methods

An extension method, in brief, is the ability to "extend" a type through some syntactical sugar. Now, I say “extend” in quotes because it really does nothing to the other type at all, it simply defines a static method in a static class and identifies the type you are "extending" as the first parameter by preceding it with the this keyword in the parameter list.

For example, you could say:

   1: // class has to be static
   2: public static class IntExtensions 
   3: {
   4:     // method has to be static, first parameter is tagged with the 'this'
   5:     // keyword, the type of the parameter is the type that is extended.
   6:     public static int Half(this int source) 
   7:     {
   8:         return source / 2;
   9:     }
  10: }

Now, even with the this keyword, this is really just a static method like any other and thus you could invoke it like:

   1: // Invoking as if it were an ordinary, static method
   2: var two = IntExtensions.Half(4);

But the magic of extension method's syntactical sugar is that you can invoke them as if they were first-class methods of the type they "extend":

   1: // Extension method behave as if they were really members of 
   2: // the type they extend, thus we can call Half() on any integer.
   3: var two = 4.Half();

Once again, this is really just syntactic sugar.  The instance of the type being “extended” is passed as the first parameter into the static method in the generated byte-code for you.  Thus, the shorter, cleaner syntax will in the end compile just like the more traditional syntax in the previous example.  But this syntactic sugar can not only shorten simple calls like the above, but can allow for chaining of multiple methods (extension and first-class both) in a very fluent way.

Let’s expand our integer extensions with a few more ideas:

   1: public static class IntExtensions
   2: {
   3:     public static int Half(this int source)
   4:     {
   5:         return source / 2;
   6:     }
   7:  
   8:     public static int Cube(this int source)
   9:     {
  10:         return (int)Math.Pow(source, 3);
  11:     }
  12:  
  13:     public static int Square(this int source)
  14:     {
  15:         return (int)Math.Pow(source, 2);
  16:     }
  17: }

Now, what if you had the above methods and wanted to take 13, Cube() it, then take Half(), then Square() the result using these methods?  If you wanted to do this using traditional static method syntax, you'd have to write:

   1: // The repetition of the type name and nesting gets confusing...
   2: var ans = IntExtensions.Square(IntExtensions.Half(IntExtensions.Cube(13)));

Ugh, that's a mess! But with extension method syntactical sugar, you get a much cleaner and easier to read result:

   1: // Much better, says take 13, cube it, half it, square it.
   2: var ans = 13.Cube().Half().Square();

So, we see there is a lot of power here to extend types in a very fluent way.  But I've only hinted at one of the things that make extension methods so very powerful. I said they could be used to "extend" any type. I don’t mean just struct or class or primitives, I mean interfaces as well.

Extending Interfaces

The great thing about interfaces is that they can be used to specify a public contract without regard to implementation details needed to satisfy that contract. This of course means that interfaces provide no method bodies.  But, many times when we are defining a complete interface, it is possible to define functionality without needing to know the implementation of the interface at all!

Consider, for example Enumerable.Count(), this is an extension method in System.Linq that will give you the count of any sequence of IEnumerable<T>.  It doesn’t care how that interface is implemented (though it has a performance short-cut for Collection implementations).  All it needs to do is to be able to know when it’s empty, and how to get the next item, both of which are specified in IEnumerable<T>, thus you can provide this functionality using only the interface of IEnumerable<T> itself.  It can be a HashSet<T>, List<T>, T[], or any other sequence of items and you can always get a Count().

As another example, let's create our own extension method to chop a sequence of IEnumerable<T> into slices of a given size. That is, if we had an array of size 32, and we wanted to divide it into slices of size 13, we should get back as output three sequences of size 13, 13, and 6.

   1: // some extension methods for IEnumerable<T>
   2: public static class EnumerableExtensions
   3: {
   4:     // first argument is the source,second is the max size of each slice
   5:     public static IEnumerable<IEnumerable<T>> Slice<T>(this IEnumerable<T> source, int size)
   6:     {
   7:         // can't slice null sequence
   8:         if (source == null) throw new ArgumentNullException("source");
   9:         if (size < 1) throw new ArgumentOutOfRangeException("size", "The size must be positive.");
  10:         
  11:         // force into a list to take advantage of direct indexing. Could also force into an 
  12:         // array, use LINQ grouping, do a Skip()/Take(), etc...
  13:         var sourceList = source.ToList();
  14:         int current = 0;
  15:  
  16:         // while there are still items to "slice" off, keep going
  17:         while (current < sourceList.Count)
  18:         {
  19:             // return a sub-slice using an iterator for deferred execution
  20:             yield return sourceList.GetRange(current, Math.Min(size, sourceList.Count - current));
  21:             current += size;
  22:         }
  23:     }
  24: }

Notice that everything we are using on source is available publically for any IEnumerable<T> since they are either public interface methods declared on IEnumerable<T>, or other extension methods provided in System.Linq

So now, we could use this method to process any sequence in slices!  For example, what if we had an array of 1000 items, and wanted to process them in parallel in lots of 10?

   1: int[] items = Enumerable.Range(1, 1000).ToArray();
   2:  
   3: // Process each slice of 10 items in parallel!
   4: Parallel.ForEach(items.Slice(10), s =>
   5:     {
   6:         foreach (var item in s)
   7:         {
   8:             Console.WriteLine(item);
   9:         }
  10:     });
  11:  

Now you can!  And with the fluent interface extension methods provide, you could easily chain the extension methods in a very easy-to-read way.  For example, what if you wanted to process the cube of all the numbers from 1 to 1000 in groups of 10?  We can chain in LINQ’s Select() extension method and our Cube() int extension to get:

   1: // Simply says select a sequence of the cube of each item, 
   2: // then slice the sequence into lots of size 10
   3: Parallel.ForEach(items.Select(i => i.Cube()).Slice(10), s =>
   4:     {
   5:         ...
   6:     });

You may have also noticed that we made our extension method check for a null on our source parameter.  This is generally considered good form.  It is possible to call an extension method off of a null instance, but many people think this is inappropriate because it would cause a problem for first-class methods.  That said, you can get a lot of power from allowing a null first argument in an extension method so I leave it up to you. 

My main piece of advice would be that if your first argument will allow null, the name should state it.  For example, you could write:

   1: public static class ArrayExtensions
   2: {
   3:     // returns length if not null, otherwise zero.
   4:     public static int NullSafeLength<T>(this T[] source)
   5:     {
   6:         return source != null ? source.Length : 0;
   7:     }
   8: }

And this would allow you to collapse this:

   1: if (myArray != null && myArray.Length > 0)
   2: {
   3:     ....
   4: }

To this:

   1: if (myArray.NullSafeLength() > 0)
   2: {
   3:     ...
   4: }

I personally don’t have a problem with extension methods like this allowing null because the name makes it obvious that this is safe.  There are those who don’t agree and never think it should be possible, though, so I leave it up to you and your team to decide what style you prefer.

To Extend? Or Not To Extend?

Well, we've seen the power of extension methods, but as with all good things, this power can be abused. All I'm trying to say is, just because you can make a many things extension methods doesn't mean that everything should be an extension method. 

For example, what would you say about this example:

   1: public static class IntExtensions
   2: {
   3:     // converts an int number of seconds to milliseconds for use in 
   4:     // Thread.Sleep() and other timeout methods...
   5:     public static int Seconds(this int source)
   6:     {
   7:         return source * 1000;
   8:     }
   9: }

I ran across this gem in some source online, I'm sure the well-meaning individual was hoping to use this to make code like this easier to read:

   1: Thread.Sleep(30.Seconds());

Which hey! That looks great and fluid! The problem is, not every integer represents time, and not every usage of time implies milliseconds.  Thus this extension method has a very localized purpose and doesn’t really apply to all integers as a whole.

Consider, what if someone took this well meaning method and did this:

   1: // Whoops.  I really meant 50 seconds!!!
   2: var timeout = TimeSpan.FromSeconds(50.Seconds());

They'd then have 50,000 seconds of wait time. The method above is tuned to return milliseconds from seconds, which neither the name nor the return type implies! An int can represent anything: days, hours, minutes, puppies, extra lives, etc.  Again, consider if someone would have employee.Age.Seconds() thinking it would convert their age in seconds, to only discover they are now 1000 times older.

Thus, you should always be careful when you create new extension methods that the problem being solved by the extension method fits both the type being extended, and the result appropriately for the domain of values.

Give a Hoot, Don't Pollute

As a final note on extension methods, one should always be aware not to let their dirty laundry air out in public. Just as it's a best practice to put types in namespaces to avoid collisions, I would put extension methods in their own namespaces as well so that users have to explicitly include the namespace to use them.

Why? Because it gives users a choice. Look at LINQ, if you want to use one of LINQ's extension methods, you must state using System.Linq to make them available (syntactically). That means that if a user doesn't want to be bothered with them, they simply don’t import the namespace and they won’t see them.

This also means that you won't pollute your IntelliSense needlessly as well. When you create extension methods in the global namespace (or some other high-traffic one) it can get annoying if every time you press the ‘.’ on an instance it shows every extension method under the sun.  You can, for example, create extension methods off of object, which means it would apply to every type.  While there are occasionally uses for extensions on object, you should be aware that that means that the extension method will show up in every IntelliSense member list when you press the ‘.’ key.  Having these extensions in their own namespace, again, will prevent this unless someone really wants it to be visible.

Summary

Extension methods are a very powerful feature of .NET, they allow you to attach functionality to "extend" a type (even interfaces) and have that method syntax behave as if it was a first-class method. This can enable very powerful and fluid interfaces which can help make code easier to use and maintain, if treated with respect and used properly.

Posted On Friday, March 8, 2013 12:47 AM | Comments (7) |

Thursday, February 7, 2013

C#/.NET Little Wonders: Explicit Interface Implementation

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Most of the time in C#, we implement interfaces implicitly. This is by far the simplest method and makes the method available both to consumers of the interface and the implementing type directly.

There are times, though, when you may want to implement an interface, but hide or change how the interface implementation is exposed in the implementing type.  This is done through explicit interface implementation, which we will discuss today. 

Implicit Interface Implementation

Implementing interfaces in C# is easy, we simply have our implementing type satisfy the interface by having it contain a member which satisfies the interface (or can be abstract of course).  The easiest way to do this is with implicit implementation.

So, for example, say we have a sample interface (yes, I could make it a generic, but bear with me for now):

   1: public interface IFactory
   2: {
   3:     object Create();
   4: }
We can implicitly implement this interface by creating a type that has a method with the same signature and return type:
   1: public class SentenceBuilder : IFactory
   2: {
   3:     // ...
   4:  
   5:     // Because this method has the same signature and return type, it
   6:     // is considered an implicit interface implementation
   7:     public object Create()
   8:     {
   9:         return “Both class and interface see this.”;
  10:     }
  11: }
When we do this, we call the same method whether we call the method from an instance of IFactory or SentenceBuilder:
   1: // same object, one as SentenceBuilder, one as Factory 
   2: var builder = new SentenceBuilder(); 
   3:  
   4: IFactory factory = builder; 
   5:  
   6: // result will be the same regardless of the reference we call from 
   7: Console.WriteLine(factory.Create()); 
   8: Console.WriteLine(builder.Create()); 

Many times, this is sufficient for our needs. But sometimes, we’d like a little bit more control of how a type implements an interface while still being required to satisfy the interface contract. This is where explicit interface implementation comes into play.

Explicit interface implementation – to hide interface member in implementing type

To implement an interface explicitly, you drop the public access specifier (all interface members are public), and predicate the method name with the interface name and dot as follows:

   1: public class HiddenSentenceBuilder : IFactory 
   2: { 
   3:     // ...
   4:  
   5:     // Notice no access specifier and interface name prefix of method name
   6:     object IFactory.Create() 
   7:     { 
   8:         return “Only IFactory will see this.”; 
   9:     } 
  10: } 

Now, if we try to use this in the same way as the implicit example, we will see something curious:

   1: // same object, one as HiddenSentenceBuilder, one as Factory 
   2: var builder = new HiddenSentenceBuilder(); 
   3: IFactory factory = builder; 
   4:  
   5: // This works, because Create() is part of IFactory's public interface.
   6: Console.WriteLine(factory.Create()); 
   7:  
   8: // Compiler error, Create() is a private part of HiddenSentenceBuilder's
   9: // interface because it was explicitly implemented.
  10: Console.WriteLine(builder.Create()); 

This is interesting and brings us to one of the first uses that we can use explicit interface implementation for: hiding an interface implementation from the implementing type. This can be useful if you need to satisfy a legacy interface, but really don’t like the way it is implemented and prefer to hide it from the common use-case scenario of calling from the class directly.

Explicit interface implementation – to implement member differently depending on usage

Another thing you can use explicit interface implementation for is satisfying an interface, but giving a different implementation if called from the implementing type directly. For example, our IFactory (by our design) returns object. But we could opt to have our OverloadedSentenceBuilder below implement it to return a string instead.

However, we can’t do this with implicit interface implementation:

   1: // Bad example, won't compile!!!
   2: public class OverloadedSentenceBuilder : IFactory 
   3: { 
   4:     // ...
   5:  
   6:     public object Create() 
   7:     { 
   8:         return “Satisfy IFactory.”; 
   9:     } 
  10:  
  11:     // Won’t compile, overloads can’t differ by return type 
  12:     public string Create() 
  13:     { 
  14:         return “Direct from implementing type.”; 
  15:     } 
  16: } 

This won’t even compile, because overloads cannot differ by only a return type. However, with explicit interface implementation, we can do this because the interface method is hidden when using the implementing type directly, so there is no conflict:

   1: // This will compile!
   2: public OverloadedSentenceBuilder : IFactory 
   3: { 
   4:     // ...
   5:  
   6:     // We get this if called from IFactory reference
   7:     object IFactory.Create() 
   8:     { 
   9:         return “Satisfy IFactory.”; 
  10:     } 
  11:  
  12:     // We get this if called from OverloadedSentenceBuilder reference
  13:     public string Create() 
  14:     { 
  15:         return “Nicer! No objects.”; 
  16:     } 
  17: } 

Now, when we call our methods again, we will call a different method depending on which reference we call through.  Notice that the method used is chosen at compile time!  This is not an override, it is a form of overloading.

   1: // same object, one as OverloadedSentenceBuilder, one as Factory 
   2: var builder = new OverloadedSentenceBuilder(); 
   3: IFactory factory = builder; 
   4:  
   5: // Calls IFactory.Create() since called through an IFactory reference 
   6: Console.WriteLine(factory.Create()); 
   7:  
   8: // Calls OverloadedSentenceBuilder’s Create() since called through an OverloadedSentenceBuilder
   9: Console.WriteLine(builder.Create()); 

So, as you can see, we can use explicit interface implementation when we want to have a different implementation when we are called directly from the class, or from the interface – or when we want to change the return type from interface’s signature.

Explicit Interface Implementation – Resolving interfaces that collide

Now, if the two examples above seem to be a rare or uninteresting use case to you, consider this case which happens far more likely: implementing two interfaces that collide.  That is, the two interfaces may have members with the same name that are incompatible (or that we want to implement differently).

For example, what if we did have both IFactory and IFactory<T> interfaces?  Perhaps IFactory was legacy before generics, or perhaps we like having plain old IFactory around for being able to collect together a group of factories regardless of what they return.  In either case, let’s assume we have:

   1: // "Legacy" form that returns as object
   2: public interface IFactory 
   3: { 
   4:     object Create(); 
   5: } 
   6:  
   7: // Generic form that returns as generic type parameter T
   8: public interface IFactory<T> 
   9: { 
  10:     T Create(); 
  11: } 

Now let’s say we wanted to implement them both. Often times with collections we will do something similar by implementing both IEnumerable and IEnumerable<T>.  However, we can’t implicitly satisfy both interfaces because of the same issues when we tried to overload it before:

   1: public class DoubleSentenceBuilder : IFactory, IFactory<string> 
   2: { 
   3:     // ...
   4:  
   5:     // To satisfy IFactory
   6:     public object Create() 
   7:     { 
   8:         return “Satisfy IFactory.”; 
   9:     } 
  10:  
  11:     // To satisfy IFactory<T>, BUT won’t compile!
  12:     // Overloads can’t differ by return type only.
  13:     public string Create() 
  14:     { 
  15:         return “Nicer! No objects.”; 
  16:     } 
  17: } 

So, once again, explicit interface implementation to the rescue!

   1: public class DoubleSentenceBuilder : IFactory, IFactory<string> 
   2: { 
   3:     // ...
   4:  
   5:     // Explicitly implement IFactory’s Create(), this will ONLY
   6:     // be visible from an IFactory reference.
   7:     object IFactory.Create() 
   8:     { 
   9:         return “Satisfy IFactory.”; 
  10:     } 
  11:  
  12:     // Implicitly implement IFactory<string>’s Create(), this will be
  13:     // visible through both DoubleSentenceBuilder and IFactory<string>.
  14:     public string Create() 
  15:     { 
  16:         return “Satisfy IFactory<string>.”; 
  17:     } 
  18: } 

Again, calling them both:

   1: // same object, one as DoubleSentenceBuilder, one as Factory 
   2: var builder = new DoubleSentenceBuilder(); 
   3: IFactory factory = builder; 
   4:  
   5: // calls IFactory.Create() since called through IFactory reference 
   6: object result2 = factory.Create(); 
   7:  
   8: // calls IFactory<string>’s Create() since called through DoubleSentenceBuilder 
   9: Console.WriteLine(builder.Create()); 

Notice that we let the more specific interface be our implementing type implicit implementation, though we didn’t have to have it this way. We could have made IFactory the implicit and IFactory<string> the explicit, or even made both explicit and hide Create() in the implementing type, or get really crazy and have explicit implementations for both and a third implementation when called from the implementing type. I think you get the point, there’s a lot of power here!

Summary

Explicit interface implementation is a handy technique for changing the way an interface implementation appears in the implementing type. You can use it to hide the interface method in the implementing type, resolve conflicting overloads with the implementing type, give different implementations between the interface(s) and/or implementing type, etc.

Posted On Thursday, February 7, 2013 11:26 PM | Comments (8) |

Wednesday, January 16, 2013

So very nearly finished... please stand by...

You folks have been so patient waiting for new material and I'm very grateful for that. I do have new things to write about, but wrapping up the move to Seattle has been very time-consuming!

Yesterday, we finally got delivery of our goods from the moving van line and have begun the task of setting things up and assessing any damage/missing items, etc. Nothing major, just time consuming to check over everything.

So again, I still think I'm on track to resume regular blogging every other week once this is all done and out of the way.

Thanks again for your patience!

-Jim

Posted On Wednesday, January 16, 2013 12:20 PM | Comments (4) |

Thursday, January 3, 2013

So much in motion!

Thanks for all your patience during my move to a new job and a new area. I've been settling into my new position here at Amazon in Seattle and am loving every minute of it so far!

Unfortunately, there's still a lot of life and work juggling at the moment. The whole team is changing to a new building this week and moving out of corporate housing and into our own apartment next week.

I'm trying to blog as I'm able, though, and hope to be able to get back to regular blogging by the end of the month.

Thanks again for your patience!

-Jim

Posted On Thursday, January 3, 2013 11:33 PM | Comments (1) |

Powered by: