Tuesday, December 20, 2011

ASP.NET Web Pages and QUnit

QUnit

Phil Haack has mentioned Web Pages a few times recently, so I thought it was worth posting here. It's essentially designed to take advantage of Razor's more concise (and generally more fun to use) syntax, and make it easy and appealing for people who want to make quick and easy web pages with a bit of server-side scripting thrown in. But who don't want to have to build a full MVC app.

In other words, to give ASP.NET the sort of quick and easy flexible feel of PHP. You can write full-blown OO PHP apps, but most people start at least with the quick and dirty option.

At first glance on that basis it's hard to see where Web Pages would fit in for me, after all, I am building full-blown MVC applications, and you generally wouldn't want to mix and match Web Pages and Controller routing within a single solution - it would make routing ambiguous.

On the other hand, Haack points out a very nice usage here, for testing using QUnit. The point is, controller actions are a bit redundant in the frontend script testing scenario, so why use them just for routing's sake?

He points out how annoyingly generic the name 'Web Pages' is too. He's right.

Wednesday, November 30, 2011

Bundling and Minification in .NET 4.5

A minified being
A minified being

.NET 4.5 (WebForms and MVC) will come with a cool new feature to help improve page load times from your web applications. CSS and JS files will be able to be bundled and minified at the folder level.

See ScottGu's post here, and a quick (1 min) video runthrough below (source).

This will leave your working files unaltered, and in their separate logical locations. But it will remove whitespace, use minify rules, and combine like files in response to browser requests.

One thing that isn't mentioned is cacheing, i.e. presumably the server caches the bundled files rather than perform the bundle operation every time a page is assembled. Will have to see how that works when 4.5 is released.

By default the bundled files within a folder are ordered alphabetically, but this can be overridden by customising Bundle objects. You also have the option of specifying CSS or JS syntax to convert to, including specifying custom rules. Pretty cool.

Friday, October 21, 2011

AJAX and Unobtrusive Javascript in MVC3

AJAX is a fundamental aspect of many web applications, and unobtrusive Javascript, supporting the Separation of Concerns (SOC) principle, has really come into it's own with the introduction of the HTML5 specification. In this post I want to introduce the built-in Microsoft MVC3 support for these features, just enough to get you off the ground.

I have embedded Pluralsight training videos into the post as I go along. The free Pluralsight training videos are often a great quick-and-easy primer to .NET framework features, which show you idealised scenarios from which you can jump off to more tailored solutions.

For each video I provide a short summary of it's contents for easy-access later.

This is the table of contents for the entire 'Introduction to MVC3' series. The videos embedded below are from the section 'AJAX and JavaScript with ASP.NET MVC 3'.

Video 1. CDNs, scripts at the bottom, and RenderSection
The first video is all about ways of laying out your scripts:

Play video
  • First it talks about the performance benefits of using CDN-hosted resources and placing <script> tags etc. at the bottom of your page (as opposed to in the <head>). In particular, unobtrusive javascript allows us to put our <script> tags at the bottom, because we are unhindered by inline javascript dependencies on <head>-loaded .js files.
  • Next, the 'magic' App_Code folder is demonstrated. Razor @helpers (concise versions of HtmlHelpers) can be dropped into this folder and will be precompiled into static methods, accessible from any view.
  • Finally, the RenderSection method is introduced. Like it's MVC2 equivalent, this method allows the master page to control page layout by defining sections. While the pages themselves can optionally define content to populate each section.
        <!-- Master-page scripts, included on all pages -->
        @Content.Script("jquery-1.4.4.min.js", Url)
        @Content.Script("jquery.unobtrusive-ajax.min.js", Url)
        
        <!-- Page-specific scripts -->
        @RenderSection("Scripts", false)
        <!-- (false means not required) -->
    </body>
</html>

Video 2. Using Ajax.ActionLink to return a PartialViewResult to a specified page element
The second video is a very straight-forward example of an asynchronous request:

Play video
  • An Ajax.ActionLink is embedded into a Razor view
  • ... and configured so that when the link is clicked, a particular controller action is called.
  • The controller action returns a PartialViewResult
  • ...and another parameter of the ActionLink directs the PartialViewResult into a page element (by specifying it's ID)

Note that we haven't written any Javascript or frontend code - we will discuss that shortly.

The view:

<h2>Reviews</h2>

@Ajax.ActionLink("Click here to see the latest review",
     "LatestReview",      //The controller action to call
     new AjaxOptions
     {
         UpdateTargetId = "latestReview", //The page id to
         InsertionMode.InsertAfter,       //fill with the
         HttpMetho = "GET"                //PartialViewResult
     })

<div id="latestReview">
    <!-- The PartialViewResult will be inserted here -->
</div>
The controller:
public class HomeController : Controller
{
    public PartialViewResult LatestReview()
    {
        var review = reviewRepository.FindLatest(1).Single();
        return PartialView("Review", review);
    }
}

The only other things discussed are using different InsertionMode's (InsertAfter, Replace etc.) This specifies how to handle content insertion to the specified <div>.

And adding an extra argument to specify an element to display while the content loads - i.e. a progress / status indicator image.

Video 3: Unobtrusive Javascript
The next video is where things get interesting. We get to see what exactly it is that our Ajax.ActionLink call spits out to the page...

Play video

...which is this:

<div id="latestReview">
    <a data-ajax="true" 
       data-ajax-loading="#progress"
       data-ajax-method="GET" 
       data-ajax-mode="replace" 
       data-ajax-update="#latestReview" 
       href="/Home/LatestReview">
           Click here to see the latest review
    </a>
</div>

All those 'data-dash' attributes (data-ajax, data-ajax-loading etc.) are a part of the HTML5 specification. Or rather, they are not. Anything prefixed by data- is considered by the specification to be a valid attribute, but is known to be there only to support dynamic features of the page. The attributes therefore are ignored by browser rendering engines and HTML markup validation services.

With these attributes carrying all of the custom data for this link's behaviour, all we need is a generic javascript file whose job it is to go looking for elements with data-ajax-* attributes, and to manipulate them to achieve the desired behaviour. This file is jquery.unobtrusive-ajax.js, provided by Microsoft, which must ofcourse be included after the main jQuery library.

3b. Unobtrusive jQuery validation
The video then jumps on to a related topic. Microsoft also happen to include an extension to the jQuery validation library: jquery.validate.unobtrusive.js. This makes validation message-handling also unobtrusive.

The video goes on to show how data annotations on model classes can be easily piped through onto unobtrusive Views.

The model:

public class Review : IValidatableObject
{
    public virtual int Id { get; set; }
    
    [Range(1, 10)]
    public virtual int Rating { get; set; }

    //etc
}

The view:

<h2>Edit</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <div class="editor-label">
            @Html.LabelFor(model => model.Rating)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Rating)
            @Html.ValidationMessageFor(model => model.Rating)
        </div>
        <!-- etc -->

Basically then the HtmlHelpers do all the javascript work for you.

I'll explain how in a minute, but as a brief aside - The data annotations are from the System.ComponentModel.DataAnnotations namespace introduced in .NET 3.5 (notice the the IValidatableObject interface). For those of us using the Enterprise Library's Validation Application Block, it seems that Enterprise Library 5.0 introduces interoperability between the two annotation frameworks, although I haven't tried this myself yet. For a quick intro to the features of the two systems, check out this Stack Overflow post.

Anyway, moving on - The way the HtmlHelpers render your javascript depends on your appSettings:

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>

Obviously the first needs to be true to render any javascript validation at all. But the second determines the method. When it is false, standard XHTML tags are rendered with a bunch of inline, on-the-page javascript. When it is true, the HTML5 data- tags are rendered and jquery.validate.unobtrusive.js (and jquery.unobtrusive-ajax.js) do all the work.

Video 4. Using Ajax.BeginForm
The fourth video shows how to use Ajax.BeginForm to create small, Ajax-only forms, such as a search query:

Play video

As you can see, it starts to get a bit obvious at this point. Here's the View...

@using(Ajax.BeginForm("Search", "Home", 
    new AjaxOptions
    {
        HttpMethod = "GET",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "searchResults"
    }))
{
    <input type="text" name="q" />
    <input type="submit" value="Search" />
}

<table id="searchResults">
    <!-- The PartialViewResult will be inserted here -->
</table>

...and you can imagine what the Controller method looks like - pretty much the same as the Controller method from video 2!

The rest of the videos go on to discuss:

So it's a bit off-topic for this article, but useful how-to's. I hope you found this article useful, and be sure to check out the rest of the Pluralsight MVC3 training videos.

Monday, October 3, 2011

Selected Items with HtmlHelpers

I came across an odd 'feature' of MVC Html Helpers today: Even if you explicitly provide a selected value when you call an option-based Helper, there's no guarantee that selected value will be used.

Suppose you are creating a view - an edit page for a Book. You declare something like this in your view. Note that we are passing in a new Author object as our currently selected item - so it shouldn't match anything and no items should be selected:

<% var selectList = 
    new SelectList(Model.Authors, "Id", "Name", new Author()); %>

<%=Html.DropDownList("book.Author.Id", selectList, 
    "Please select")%>

The fourth argument to your SelectList constructor is a new Author object. As such when you view your edit page you would expect the drop-down to default to "Please select".

In reality though, the drop-down defaults to the author associated in your model..? This may be the behaviour you normally want from an edit page, but when your business rules suggest that the field not be pre-populated, you can't live up to it without a mild hack.

What's happening is the Html Helper is looking at your View Model object, for an item that looks like the first argument: "book.Author.Id"

When it finds it, the Helper is favouring that Id value over your suggestion. Not exactly putting you in the driving seat is it?

One workaround? It's not the nicest-looking, but set the View Model value to what you want just before calling the Helper:

Model.Book.Author = new Author();
<% var selectList = 
    new SelectList(Model.Authors, "Id", "Name", new Author()); %>

<%=Html.DropDownList("book.Author.Id", selectList, 
    "Please select")%>

It may not be pretty, but it works.

Friday, July 22, 2011

Lambda Expressions in C#

In a previous article I introduced delegates and anonymous delegates. In this article I intend to explain the fundamentals of Lambda expressions by building on our knowledge of delegates. It's useful to get a proper handle on delegates before delving into Lambdas, because Lambdas are just anonymous delegates in different clothing.

A Quick Example
At the end of my post on delegates, I introduced a common scenario where you might want to use an anonymous delegate to find an item from a list:

class AdHocSearch
{
    static void Main()
    {
        List<Book> bookDb = new List<Book>();
        bookDb.Add(new Book(){ title = "Romancing the Stone" });
        bookDb.Add(new Book(){ title = "Wuthering Heights" });
        
        Book foundBook = bookDb.Find(delegate(Book candidate)
        {
            return candidate.title.Equals(
                            "Wuthering Heights");
        });

        Console.WriteLine(foundBook.title);
    }
}

However the same code can easily be refactored to use a Lambda expression (if you use ReSharper just hit Alt+Enter and it will refactor for you):

class AdHocSearch
{
    static void Main()
    {
        List<Book> bookDb = new List<Book>();
        bookDb.Add(new Book(){ title = "Romancing the Stone" });
        bookDb.Add(new Book(){ title = "Wuthering Heights" });
        
        Book foundBook = bookDb.Find(
            candidate => candidate.title.Equals(
                                "Wuthering Heights"));

        Console.WriteLine(foundBook.title);
    }
}

The portion highlighted is the Lambda expression, and it does the same job as the delegate in the first code-block. However it does it in a way which is slightly different - it is more concise, and it's declaration is less explicit.

Let's start from the top - the Lambda operator.

The Lambda Operator
You can tell you are looking at a lambda expression when you see the lambda operator (=>). This operator can be read as "goes to":

x => x * x

So this expression (above) is read as "x goes to x times x".

How do we Get from Delegate to Lambda?
Let's explain the above expression by showing how it would look in familiar, delegate form. Then we can alter it step by step until it becomes a lamba expression again. Here's the fully written-out delegate equivalent of the above statement (below). I have written this in a way which should be familiar from my previous post on delegates:

public delegate int Square(int i);

void Main()
{
    Square square = delegate(int i)
    {
        return i*i;
    };
}

In the code-block above, the first thing to notice is that we have a named delegate type - it's name is Square. This is the first line in the code-block, the declaration that essentially says (in English) "There is a delegate type named Square, it has a single int input parameter, and an int return type."

Inside the body of the Main method, we have then instantiated an instance of Square, (named lower-case square), and assigned an anonymous delegate to it.

Step 1: Anonymise the Delegate Type
Well now, we are going to anonymise the delegate type aswell as the delegate. Anonymising means declaring the same behaviour, but without specifying a name. So in English: "There is a delegate type named Square, it has a single int input parameter, and an int return type".

Since we are no longer giving it a name, we must declare it at the same time as assigning a value to it, and therefore now the whole thing is enclosed within one statement. Remember, we are still naming the variable (lower-case square), but we are no longer naming the type (was init-capped Square):

public delegate int Square(int i);

void Main()
{
    Square square = delegate(int i)
    {
        return i*i;
    };
}

//becomes

void Main()
{
    Func<int, int> square = delegate(int i)
    {
        return i*i;
    };
}

To do this we used a type named Func<T, TResult> (see the definition here), which was introduced in C# 3.5. This class allows us to encapsulate a method as a reference-type, and pass in a couple of generic type parameters describing the argument and return type respectively: <int, int>.

You'll notice that there are several variations on Func, each with a different number of generic type parameters. You can encapsulate a method with up to 16 arguments, and there is a similar family of classes to deal with methods with no return type. Any method you assign to an instance of one of these types has to have matching input parameters and return type, and you can see in the code-block above this is the case.

Step 2: Switch to Lambda Syntax
Now let's convert the delegate on the right side of that assignment operation into a lamda expression:

Func<int, int> square = delegate(int i)
{
    return i*i;
};

//becomes

Func<int, int> square = i => i * i;

And there we have the same statement we started with. It uses the same variables to do the same thing and return the same value - but with different syntax.

The first thing you notice is how concise it is, even though it does exactly the same job. On the left side of the operator, we always have the input parameters.

  • left-of-the-operator - input parameters,
  • right-of-the-operator - expression or statement block

Remember, the operator is read as "goes to". So a lambda is always read as "input (goes to) expression", or "input (goes to) statement block".

Inferred Typing
With the delegate version we had to specify the type of the input parameter, when we said: delegate(int i). However with lambdas the compiler infers the type of i from it's usage. The compiler sees that we are assigning the expression to a strongly-typed Func object with generic type parameteres <int, int>. So it knows and doesn't need to be retold that the input parameter i in the expression is an int.

Don't make the mistake of thinking this is loosely-typed. Loose-typing is not possible in the .NET Framework. This is inferred typing, which is still very much strongly-typed. Type usage is inferred by the compiler on initialisation and cannot change. It is part of the suite of implicit-typing functionality introduced in C# 3.0, including:

In fact, one of the main benefits of lambda's, is they are a simple way to make many previously un-type-safe operations type-safe. Take a quick look at Mauricio Scheffer's blog here, where he has used lambda's to replace string literals. You see this type of usage a lot in .NET frameworks and packages nowadays.

In the first example in the first code-block of this post, without Lambdas or delegates the Find method would only be possible by passing in string literals representing the desired candidate properties. And you can also see, for example, from my post on StructureMap IoC, that statement lambdas are now the preferred initialisation approach (though the previous approach was also typesafe).

Specifying Input Parameters
If you want to override the compiler's inferred usage, you can use brackets on the left-side of the lambda operator to specify input parameters:

Func<int, int> square = (int i) => i * i;
Or, if you have no parameters to pass in, just use empty brackets:
Func<int> noParams = () => 5 * 5;

I have to admit i'm not sure yet where or when this would be useful.

Expression Lambdas vs. Statement Lambdas
So far we've only been using Expression Lambdas, which means that on the right-side of the lambda operator there is one, single expression. This is generally useful when you are trying to apply a function, such as Square above, or trying to apply a predicate, such as the List.Find example at the top of this article.

However you can construct multi-line, procedural lambdas if you wish, by using curly braces:

Action speakToWorld = n =>
{
    string s = n + " " + "World";
    Console.WriteLine(s);
};
speakToWorld("Hello");

Action is ofcourse the cousin of Func, but never returns a value (see the reference page here).

Expression Trees
One final thing to note here is the broader context within which both lambda's and delegates exist. We have moved into an arena where functionality now has the same status as value. What I mean is that we are used to assigning and manipulating values (and objects encapsulating values) within variables. Now it is just as easy to build and manipulate functionality. Expression trees are an example of that.

Earlier we used Func and Action to store our method pointers. These allow truly anonymous references to executable code. But these classes can be assembled and re-assembled in their own right, as components of an Expression object.

Have a quick look at the MSDN on Expression Trees:

"Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y."
"You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries."

A quick example from the-code-project:

ParameterExpression parameter1 = 
    Expression.Parameter(typeof(int), "x");

BinaryExpression multiply = 
    Expression.Multiply(parameter1, parameter1);

Expression<Func<int, int>> square = 
    Expression.Lambda<Func<int, int>>(multiply, parameter1);

Func<int, int> lambda = square.Compile();
Console.WriteLine(lambda(5));

In the code-block above, we have done the same thing our simple lambda expression from earlier does - square a number. It is much more verbose, yes, but look at the types on the last two lines before Console.WriteLine. We created a dynamic Expression object, which can be altered and assembled ad-hoc however you like at runtime - and then Compile()'d into executable code, and run - again, all at runtime.

In other words, you can have your code assemble more code as it runs. Or in other words again, you can have your code treat itself in the same, flexible way it used to only be able to treat data and values.

Aside from generating dynamic queries, what does this allow us to do? As this stack-overflow page points out, we can hand the power of code customisation over to users. Ever made a 'form builder', allowing users to customise post-driven dynamic webpages? I can't imagine how we did that in the past but they've just got a whole lot easier, and semantically correct. Or what about user-customised workflows? Ditto.

Further Reading

Thursday, July 21, 2011

Introduction to Delegates in C#

What is a delegate? Most articles dive straight into the technical stuff, but I think it makes it easier to learn when you start by looking at the metaphor - I will dive right into the practical example straight afterwards.

So first of all, what makes the word 'delegate' such an apt keyword?

The Metaphor
According to Wikipedia, a delegate is a person who is similar to a representative, but "delegates differ from representatives because they receive and carry out instructions from the group that sends them, and, unlike representatives, are not expected to act independently."

Imagine a government department is employing two private companies to carry out litter collection across two districts. The government are responsible for preparing the contracts, and intend to use a standard template contract for both private companies. But the two private companies have different operating practices, and each want to tailor their respective contracts to suit their own particular needs.

They each send a delegate to meet the government and make amendments to their respective contracts. Each delegate is briefed by their respective companies before they leave, so that they know exactly what their instructions are. Each delegate arrives intending to do the same thing - amend a contract. But their instructions and boundaries on how they can do that are different - and are defined clearly by the respective senders.

I'll end the metaphor here, because I don't want to lock into one example. But having that sense of what a delegate is should make the rest of this article easier to read.

Declaring a Delegate Type
First, let's declare a publicly accessible delegate type:

//Declare a delegate type
public delegate void BookProcessingDelegate(Book b);

It is important at this stage to understand that what we have defined is not a delegate but a delegate type. Each instance we later instantiate of this type will be an actual delegate.

Delegates are usually declared not as class members, but as peers of classes or structs, i.e. at the same level. This is because declared delegate types are types in their own right. They can ofcourse, also be declared nested inside a class (just like a class can be declared nested inside a class).

In other words, a delegate is an example of a reference-type, and is stored on the heap and accessed via a pointer (see my article on types, the stack and the heap).

Instantiating and Assigning a Delegate Method
Having declared our delegate type, there are three things we need to do to make use of it:

  1. Define a method (write some instructions)
  2. Instantiate a delegate and assign the method to it (brief the delegate of our instructions)
  3. Send the delegate off to do business on our behalf

I'm going to use a variation of the 'classic' delegate example, and note that I've commented numerically the implementation of the bullet points above:

//Declare a delegate type
public delegate void BookProcessingDelegate(Book b);

public class Book
{
    public string title { get; set; }
}

public class BookDB
{
    private IList<Book> books;

    public void ProcessBooks(BookProcessingDelegate del)
    {
        foreach(Book b in books)
        {
            // Call the delegate method
            del(b);
        }
    }
}

class Program
{
    //1. Define a method
    private static void PrintBookTitle(Book b)
    {
        Console.WriteLine(b.title);
    }

    static void Main()
    {
        BookDB bookDb = new BookDB();

        //2. Instantiate a delegate, and assign the method
        BookProcessingDelegate printTitles = PrintBookTitle;

        //3. Send the delegate off to do work on our behalf
        bookDb.ProcessBooks(printTitles);    
    }
}

When we assign the method to the delegate (item 2 above), we are actually assigning to the delegate a pointer to the method. Then, when the BookDB.ProcessBooks method uses (invokes) the delegate, it follows the pointer and actually invokes the referenced method.

Logically, it is exactly the same as if the body of the referenced method had been declared inside of BookDB. But ofcourse it wasn't, and that's the key to the usefulness of delegates - i'll discuss this in more detail shortly.

But first of all let's explore two more ideas - anonymous delegates, and multicast delegates.

Anonymous Delegates
In the above example, we assigned a named method which was a private class member (namely PrintBookTitle). If that method is only going to be used for this one specific purpose, it can be much more convenient to declare an anonymous method.

What follows is exactly the same code block as above, but now the PrintBookTitle method has been anonymised, causing steps 1 and 2 to become one statement:

class Program
{
    static void Main()
    {
        BookDB bookDb = new BookDB();

        //1. Define a method AND
        //2. Instantiate a delegate, and assign a method
        BookProcessingDelegate printTitles = delegate(Book b) {
            Console.WriteLine(b.title);
        };

        //3. Send the delegate off to do work on our behalf
        bookDb.ProcessBooks(printTitles);    
    }
}

Anonymous delegates are more concise, and they are the foundation of lambda expressions, which I discuss in another article.

Multicast Delegates
It's another odd word, but multicast is based on another metaphor. Check out the link to get a quick sense of that, but it's simple enough anyway. You can assign more than one method to a delegate. The delegate will respond when invoked, by executing each method in order:

class Program
{
    private static void PrintLower(Book b) {
        Console.WriteLine(b.title.ToLower());
    }

    private static void PrintUpper(Book b) {
        Console.WriteLine(b.title.ToUpper());
    }

    static void Main()
    {
        //Instantiate a delegate, and assign TWO methods
        BookProcessingDelegate printTitles = PrintUpper;
        printTitles += PrintLower;

        //You can also use the -= operator to remove methods
        //from the 'invocation list'
        printTitles -= PrintLower;
    }
}

You can add and remove methods to your heart's content. The resulting list of methods which must be called on invocation of the delegate is referred to as the delegate's invocation list.

If the delegate has a return value, only the value returned by the last method in the invocation list will be returned. Similarly, if the delegate has an out or ref parameter, the parameter will end up being equal to the value assigned in the last method in the invocation list (see also my article on parameter passing in C#).

What Are Delegates Useful For?
As we have seen, delegates give us the ability to assign functionality at runtime. This adds to our toolbox of assignment operations - we all know how easy it is to assign values, or references to objects. Now we can assign functionality too.

Look back to the first, main code-block of this article. It should be clear that any class, anywhere in your application that chooses to call BookDB.ProcessBooks can do so and provide it's own specific, tailored functionality. The Program class happens to have sent one particular type of functionality (printing to the console), but any delegate can point to any method implementation.

Without delegates, the creators of the BookDB class would have to have thought up in advance every possible thing that callers might want to do with the Book list - and provide lots of methods to cover all those bases. In doing so, the BookDB class would be taking on responsibilities that are not within it's problem domain.

The other way to achieve the same functionality without delegates would be for the BookDB to expose it's internal list as a property, or via an access method. The Program class could then iterate over the collection itself. But this approach would mean that the Program class was shouldering responsibilities that are not within it's domain - iterating over a collection.

Delegates therefore provide an elegant solution which helps achieve the Seperation of Concerns principle within your application architecture.

A Common Usage - Ad-Hoc Searching
There are lots of places in the .NET Framework where you can use delegates, and their newer equivalent, lambda expressions. We'll take a look at one example, by altering our BookDB code a little. Let's say you want to find a book with a particular title, from a list of Book items:

class AdHocSearch
{
    static void Main()
    {
        List<Book> bookDb = new List<Book>();
        bookDb.Add(new Book() { title="Romancing the Stone" });
        bookDb.Add(new Book() { title="Wuthering Heights" });

        Book foundBook = bookDb.Find(delegate(Book candidate)
        {
            return candidate.title.Equals("Wuthering Heights");
        });

        Console.WriteLine(foundBook.title);
    }
}

If you couldn't use a delegate, you would have to manually iterate over the list. But fortunately for us, the List<T>.Find() method will accept a delegate function which describes how to apply a condition which determines a match for us. This leaves the job of iterating the collection, with it's associated efficiency concerns, in the correct problem domain - the domain of the List.

Quick Runthrough
For a nice, quick, concise primer on the subjects I've discussed above, check out this Youtube video:

I don't think it stands up as a learning resource in it's own right, but as a primer it's quite well organised.

Further Reading
This is quite a nice delegates tutorial on MSDN.

Wednesday, July 20, 2011

Pass by Value and Pass by Reference in C#

This article is a quick explanation of C#'s handling of pass-by-val and pass-by-ref. If you haven't already done so, it's a worth getting to grips with the heap and the stack - that article will also explain the relationship between value types, reference types and pointers, which will be really useful.

Value-Types
By default, value types are 'passed-by-value' into C# methods. This means that inside the body of the called method, the value instance can be changed or re-assigned without affecting the instance of the value in the caller.

static void Main(string[] args)
{
    int i = 1;
    Console.WriteLine(i); // prints 1
    MyMethod(i);
    Console.WriteLine(i); // prints 1
}

static void MyMethod(int i)
{
    i = 2;
}

If you want to override this behaviour, you can use the ref keyword or out keyword:

static void Main(string[] args)
{
    int i = 1;
    Console.WriteLine(i); // prints 1
    MyMethod(ref i);
    Console.WriteLine(i); // prints 2
}

static void MyMethod(ref int i)
{
    i = 2;
}

You can use the ref or the out keyword, the only difference it makes is that ref needs the value to have been initialised before it is passed.

The compiler will issue an error if you try to send an unassigned variable with the ref keyword, but it will let you send happily using out. Ofcourse, if you don't have logic to handle the unassigned out variable in the target method you will get a runtime exception anyway.

Reference-Types
There really is no way to pass reference-types other than by reference. So although you can use the out and ref keywords with an object, there really isn't much point:

static void Main(string[] args)
{
    MyClass myObj = new MyClass();
    MyMethod(ref myObj);            //not much point
}

If you want to pass a reference-type variable by-value, you need to start thinking about cloning the object, which is a whole new subject matter in itself. If you simply want to prevent the passing object from being altered you might want to consider making the class immutable, but in any case that's outside the scope of this article.

More examples