Posted on July 26, 2008 21:47 by swilliams

Delegates have come a long way since they were introduced in .NET 1.0. Back then they were only a way to refer to existing methods as variables. 2.0 allowed methods to be inlined, making them "anonymous." The 3.5 Framework does not introduce any new concepts regarding delegates, but it makes writing them much, much quicker and cleaner.

Let's reuse the example from the last post. C# 2.0's syntax for anonymous methods looked like this:

private delegate void ItemAction(ListViewItem item, int index);

private void ActOnListView(ItemAction action) {
    for (int i = 0; i < this.listView1.Items.Count; i++) {
        ListViewItem item = this.listView1.Items[i];
        action(item, i);
    }
}

public void HighliteEven() {
    this.ActOnListView(delegate(ListViewItem item, int index) {
        item.BackColor = index % 2 == 0 ? Color.Red : item.BackColor;
    });
}

The HighliteEven() method can be written with C# 3.0 as:

public void HighliteEven() {
    this.ActOnListView((x, y) => x.BackColor = y % 2 == 0 ? Color.Red : x.BackColor);
}

Whoa, where did that => thing come from? That's the new shorthand for creating an anonymous method. All it does is compresses delegate(Type object){ into something smaller. The (x, y) parameters do not need Type declarations because they are inferred from the delegate's signature as a ListViewItem and a Int32 (you'll even get intellisense on them).

This is what allows you to use all of the slick extension methods added to the standard collection classes:

List<string> stuff = new List<string>();
if (stuff.All(s => s.Length > 10)) {
    Console.WriteLine("all strings have at least 10 characters.");
}
string[] myName = stuff.Where(n => n.StartsWith("Scott"));

Single object parameters do not need parentheses, and delegates with no parameters use empty ones: ().

This type of expression is often called a Lambda. Technically, you can have multiple line lambdas, the convention is to stick with a single one1. Multiple lines of code with this syntax can quickly become messy and hard to read. Stick with the old delegate() { } syntax instead if you need it.

[1. I'm not even going to show or link to the syntax, since you shouldn't use it.]

If you are familiar with Python or Ruby (and others) this style should be familiar to you.

	# a lambda in Python
	sq = lambda x: x * x
	sq(5)
	# returns 25

	# a lambda in Ruby
	sq = lambda {|x| x * x}
	sq.call(5)
	# returns 25

.NET also provides a few prefab helper delegates. Action was provided in the 2.0 framework. It's signature looks like this:

public delegate void Action(T obj);

It has a few overloads to take up to four parameters. So, our sample code up top can be rewritten as:

private void ActOnListView(Action<ListViewItem, int> action) {
	// snip
}

Removing the ItemAction definition.

For methods that need to return something, .NET 3.5 offers several versions of a delegate called Func. The most basic is Func<TResult>(), which takes no parameters and returns an instance of whatever TResult is set to. Func<T, TResult> takes a single parameter, of type T, and also returns a TResult. Like Action, Func provides overloads for up to four parameters. These can all be backported to .NET 2.0, since they don't use any 3.5-only features:

public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T obj);
// and so on

The various forms of Func are used throughout the LINQ enabled extension methods of the 3.5 Framework.

The single biggest thing to be aware of is that overuse of delegates makes code difficult to read, especially for the neophyte. If you have a particularly hairy situation, say one that has three or more nested generics and a few lambdas, all on one line, consider splitting it apart in order to increase readability. The compiler won't care, but maintainers will appreciate it.

If you have never encountered them before, delegates can feel a little awkward at first, but once you get used to them, especially with C# 3.0's lambda syntax, you won't want to go back.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on June 30, 2008 10:26 by lbrown

Ever wonder how that magical tag called ‘[Serializable]’ placed at the top of a class enables it to be deconstructed into XML that can be tranmitted through firewalls or persisted in a files or database tables? Not to get too technical but attribute classes are embedded into the tagged classes’ metadata at compilation and can be reflected on to perform any function you desire. 

The following example provides a real world scenario where custom attributes can enhance one’s  coding experience.  I can’t tell you how many times I have to use stored procedures that have a million parameters each having the capacity to be null.  Think of a search procedure that has ten criteria.  If I was coding this with the SqlCommand class, I would have to write a method that creates each SqlParameter and populates it with DBNull or some value. There are over ninety nine combinations in this scenario.  That really cuts into my ebay time.

If I wrote an attribute that could turn a class into a SqlCommand with populated values and could be serialized in session or view state and reduce my time coding, life would be wonderful.  In addition, if I wrote a tool that generated the code for the attributed class, my evil plan to do no work would be complete!

I have attached a solution that contains all the code mentioned above.

AtrributeSolution.zip (51.43 kb)



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 13, 2008 16:16 by swilliams

One of the hip new features of C# 3.0 is the built in support for lambdas:

Func<int> sq = x => x * x;
sq(5); // equals 25

This is very fancy, but sometimes you need to perform a lambda that has no argument. The syntax for that is simply "()".

Func<object> doStuff = () => Console.WriteLine("stuff has been done"); 
doStuff();


Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 10, 2008 19:03 by swilliams

Last time, we tweaked our code to make it a little easier to understand and maintain. So that means we get to dirty it up again!  Our current object model has very simple mapping of one table to one class, with no associations between them. In the real world, this doesn't happen too often (and if it does, you are probably doing something wrong). A relational database has relations. Crazy, yes, but it means our model must be able to handle that.

Let's say then, that the Person object can possess all of the TpsReport objects they have created. To represent that, we'll need to update three things, our table structure, the classes, and the mapping file.

More...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 7, 2008 12:32 by swilliams
In the last post, we created the basic outline of a project that started to decouple LINQ enabled objects from the data layer. We have an ILoader interface that defines what a loader looks like, and a LinqLoader class that uses LINQ To SQL to pull data from a database.

The biggest problem with the code is that it is rather messy. Strings are hard-coded, and worse, the UI layer needs to know the data layer to create the proper ILoader. So before we dig any deeper with LINQ, let's improve the code quality in our app.

More...

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 5, 2008 08:14 by swilliams

(reposted because something ate this the first time)

Each major release of the .NET framework and Visual Studio has at least one killer feature that makes developers stuck in prior versions pine longingly for it. With .NET 3.5 and Visual Studio 2008, that big one is LINQ. The reason being is that it provides built in OR/M functionality with SQL Server. To put it succinctly: it can take database tables and create .NET classes and the code to bind them to each other.

It's pretty hot stuff, or it is until you look at your business objects and realize that they are directly tied to your data layer. This is known as "Tight Coupling" and is a Bad Thingtm. It is also not very testable - to test anything having to do with your objects will result in the database being modified.

So does this mean we have to chalk up LINQ to SQL as another neato feature that is pretty but only suitable for marketing demos? Not necessarily; there are ways that you can detach the coupling, but it's not the easiest thing in the world.

More...

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 1, 2008 07:57 by mcollins

In this post, I wanted to introduce you to a new feature that is definitely more than welcome in .NET 3.5: auto-implemented properties.  Auto-implemented properties are a shorthand notation for declaring simple properties in classes.

Let's say that I'm developing a class representing a student for an educational software package.  In the past, I would have defined the class using the following code:

   1: public enum Gender {
   2:     Female,
   3:     Male
   4: }
   5:  
   6: public class Student {
   7:     private DateTime birthDate;
   8:     private string firstName;
   9:     private Gender gender;
  10:     private string lastName;
  11:  
  12:     public DateTime BirthDate {
  13:         get { return birthDate; }
  14:         set { birthDate = value; }
  15:     }
  16:  
  17:     public string FirstName {
  18:         get { return firstName; }
  19:         set { firstName = value; }
  20:     }
  21:  
  22:     public Gender Gender {
  23:         get { return gender; }
  24:         set { gender = value; }
  25:     }
  26:  
  27:     public string LastName {
  28:         get { return lastName; }
  29:         set { lastName = value; }
  30:     }
  31: }

This is a lot of code for a simple class.  Fortunately, in .NET 3.5, we can reduce this amount of code and make it even simpler:

   1: public enum Gender {
   2:     Female,
   3:     Male
   4: }
   5:  
   6: public class Student {
   7:     public DateTime BirthDate { get; set; }
   8:     public string FirstName { get; set; }
   9:     public Gender Gender { get; set; }
  10:     public string LastName { get; set; }
  11: }

Using auto-implemented properties, the .NET language compiler will automatically generate the simple data fields for the class and implement the getter and setter methods for each property.

The only thing to consider when using auto-implemented properties is that, in the past, inside the methods of my objects I would use the fields instead of the properties when I needed to access the object instance data.  When using auto-implemented properties, you will only be able to use the properties in order to get to your object's data, but that shouldn't be any more inefficient because the compiler will most likely optimize the property access.

Technorati tags: ,


Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 1, 2008 07:55 by mcollins

The next new feature of .NET 3.5 that I want to blog about is the addition of object and collection initializers.  Here's the final simplified Student class definition from my previous post:

   1: public enum Gender {
   2:     Female,
   3:     Male
   4: }
   5:  
   6: public class Student {
   7:     public DateTime BirthDate { get; set; }
   8:     public string FirstName { get; set; }
   9:     public Gender Gender { get; set; }
  10:     public string LastName { get; set; }
  11: }

When creating a Student object in the past, I might have used code such as the following to initialize the object:

   1: Student student = new Student();
   2: student.FirstName = "Michael";
   3: student.LastName = "Collins";
   4: student.BirthDate = new DateTime(1975, 1, 31);
   5: student.Gender = Gender.Male;

As an alternative, I might have enhanced my Student class to have constructors where I would pass in the values:

   1: Student student = new Student("Michael", "Collins",
   2:     new DateTime(1975, 1, 31), Gender.Male);

The problem with the second approach that uses a constructor is that if I go back and add more properties to my Student class, then I'm required to modify the constructor by adding new parameters to the constructor.  If I modify the constructor, then I have to go back and modify all of the code that uses the constructor.  If third-parties are using my Student class, then they have to be notified so that they can change their code.  Basically, there are a lot of code changes.  The first approach, while using more lines of code, is more adaptable to the situation where I add more properties to the class without breaking existing code.  However, the downside is that the constructor approach is easier and requires less code.  It can be tedious, especially when you're creating multiple objects, to sit there and write the same property setter code over and over again.  But .NET 3.5 helps us out just a little with object initializers.

Object initializers are a nice mix of property setters and constructor syntax.  Using an object initializer, I can rewrite the above code samples like this:

   1: Student student = new Student { FirstName = "Michael", LastName = "Collins",
   2:     BirthDate = new DateTime(1975, 1, 31), Gender = Gender.Michael };

A lot simpler, isn't it?

Where it gets even better is when we can mix object initializers with collections.  Imaging the scenario where I want a collection of students.  If I take my first approach to initializing the Student objects to create a collection of students in memory, I have to write a lot of code to initialize each collection member.  With collection initialization and object initialization, I can write the following:

   1: var students = new List<Student> {
   2:     new Student { FirstName = "Michael", LastName = "Collins", ... },
   3:     new Student { FirstName = "Scott", LastName = "Williams", ... },
   4:     new Student { FirstName = "Joe", LastName = "Wilson", ... },
   5:     new Student { FirstName = "Jack", LastName = "Benson", ... }
   6: };

The above code sample also is using the var shortcut for local variable definitions.  This is another new feature in .NET 3.5, in that you still get the same type-safe code, but you don't need to declare the type of each local variable.  Instead, at compile time, the compiler infers the actual type of the variable.

To give you an idea of how easier collection initialization makes building collections, here's how it would have been done previously.  Of course, I'm cheating here as well, because I'm still using object initialization.

   1: var students = new List<Student>();
   2: students.Add(new Student { FirstName = "Michael", LastName = "Collins", ... });
   3: students.Add(new Student { FirstName = "Scott", LastName = "Williams", ... });
   4: students.Add(new Student { FirstName = "Joe", LastName = "Wilson", ... });
   5: students.Add(new Student { FirstName = "Jack", LastName = "Benson", ... });

While we end up with more-or-less the same amount of code, I very much prefer the first example that uses collection initialization when you know what objects that you want to put into the collection.

Technorati tags: ,


Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5