Profile picture Schedule a Meeting
c a n d l a n d . n e t

More Effective C# Notes: Generics

Dusty Candland | |

I’ve been reading the More Effective C# book by Bill Wagner. I’m going to blog some of my notes and thoughts on the book. If you find some of this stuff useful you will want to pick up a copy of the book.

Use the least amount of constraints on type parameters as possible. I’ve run into this, and besides limiting the usefulness of your class, in many cases you need to implement an interface or add a default constructor to get classes to compile. And ultimately your generic class ends up not being very generic.

In order to help achieve the above, you can use methods or delegates to enforce a specific needed operation. Whatever constraint you were going to have you could create a delegate that needs to be passed in and remove the constraint.

If you need to create new instances of the type parameter, you need to make sure you dispose of it correctly if it implements IDisposable. If it’s created as an instance member your generic classes needs to implement IDisposable. This simple pattern can be used for method scoped instances.

T instance = new T();
using (instance as IDisposable)

instance.MethodCall();<style type="text/css">.csharpcode, .csharpcode pre

{

font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/

}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{

background-color: #f4f4f4;
width: 100%;
margin: 0em;

}
.csharpcode .lnum { color: #606060; }

Remember that the type parameter is always going to be the best match in an overloaded method search. As, such you can use run-time type checking to optimize for performance. I would not bother doing this until you know that it’s a performance issue. Or unless your making a closed source framework.

Use generic methods unless the type parameter is going to be an instance field. This makes the generic class easier to use as you don’t need a new class for each different type parameter being used. Also these types of methods lend themselves to becoming extension methods.

Again these are just some of my notes, the book, like the previous one, is worth a full read.

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: