Archive

Archive for the ‘C# 3.0’ Category

Automatic Properties and StackOverflowException

January 14, 2008 2 comments

I’ve written a couple of times before about Automatic Properties, a tiny little feature that I have really come to enjoy. Remember that an Automatic Property looks something like this:

// An Automatic Property
public string FirstName { get; set; }

I’ve also written that if you want to add any behavior to this property, then you must create a variable and complete the code just as you would have a regular property. I was coding the other day and I had to transform add some behavior to what had been an automatic property. For grins, I wanted to see what I could get away with, so I tried a couple of different approaches.

First, I really only wanted to add behavior to the Setter, so I tried leaving the Getter as is:

// Will not compile
public string FirstName
{
    get;
    set
    {
        FirstName = value.TrimEnd(new char[] { ' ' });
    }
}

This will not compile, resulting in the following error:

‘ConsoleTestBed.Person.FirstName.get’ must declare a body because it is not marked abstract, extern, or partial

OK, so no joy there, I have to fill out the Getter. But notice in the Setter block there is no error! So I fill out the Getter and it looks like this:

// This compiles
public string FirstName
{
    get { return FirstName; }
    set
    {
        FirstName = value.TrimEnd(new char[] { ' ' });
    }
}

This compiles just fine. What I’m hoping at this point is that the Compiler will recognize what I am doing (given its context) and still create the variable for me. However, when I run it, I get a StackOverflowException. What you have probably figured out, and what I was afraid of, is that by referencing the Property name within the Property, I have created a recursion problem. So, unfortunately, I was originally correct: in order to make these changes work, I have to create a variable to support the Property:

// This compile AND works
private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value.TrimEnd(new char[] { ' ' });
    }
}

So if your program throws a StackOverflowException on a Property, be sure that you haven’t created a Recursion issue. Maybe someday the C# compiler guys can find a way to make this work based on the Context, or maybe a Property Attribute.

Advertisements
Categories: .NET 3.5, C# 3.0

Extension Methods Update

January 2, 2008 Comments off

I’ve been working on some more Extension Method stuff (I’ll be sharing soon!), and in the process I updated the DevelopingForDotNet.Extensions namespace.? Here is a list of the updated methods:

  • DateTime.GetDateString() – accepts an Enum for the format of the DateTime string (Enum is part of the namespace).? Overridden to allow control over the separator character.
  • DateTime.TwoDigitYear() – returns the Year of the DateTime in two digit format.? Great for aligning with legacy data.
  • IDictionary.ExecuteOnValues<K, V>() – performs an Action<V> on each Value in a Dictionary.
  • decimal.ConvertToMoney() – Converts any decimal to a two decimal precision numeric.? Overridden to allow control over rounding behavior.
  • decimal.GetMoneyString() – Converts a decimal to Money and returns a properly formatted string.
  • decimal.GetUSMoneyString() – implements the above, but specific to US Currency.? Also overridden for rounding.
  • long.ConvertToWords() – converts a long value to spelled out words.
  • decimal.GetDecimalNumbers() – returns just the decimal portion to the right of the decimal point as an integer.
  • StringBuilder.Clear() – clears all text from a StringBuilder (sets its length to 0).

Be sure to download the update.? Keep watching, there will be more to come.

Categories: .NET 3.5, C# 3.0, Free Code

Upgrade your C# Skills part 4 – LINQ to Objects

January 2, 2008 7 comments

If you’ve been following along recently, you’ll know that I have immersed myself in VS2008 and .NET 3.5. No discussion of these new technologies would be complete without addressing LINQ (Language Integrated Query). My problem is that LINQ has been written about to death by a lot of more qualified people than myself. With the other articles in this series I felt like I had something to offer, but here I am not so sure. So here is what I will do: I will hit the lowlights. Instead of showing you how to use LINQ, which you can get just about anywhere, I’m going to focus on when and why to use LINQ. I’ll also show you how to write your own Types that can be consumed by LINQ.

LINQ actually comes in five flavors:

  • LINQ to Objects – using LINQ to query Collections.
  • LINQ to SQL – using LINQ to directly query SQL Server databases.
  • LINQ to Datasets – using LINQ to query disconnected data stored in a DataSet.
  • LINQ to XML – using LINQ to create, read, manage, and query XML formatted data.
  • LINQ to Entities – using LINQ to query databases via the Entity Data Model Framework.

In this article, I will only cover LINQ to Objects as it provides the foundation for all the others. I will most likely cover LINQ to SQL and LINQ to DataSets in future articles. I have never been much of an XML user, but I may become one with the power of LINQ to XML: if I do, I will write about that at the appropriate time. Same goes for LINQ to Entities: the Entity Data Model Framework should be released sometime in the spring, and I will probably wait until then to cover that topic. So enough of me telling you what I’m not going to write about: let’s get to the real material.

IEnumerable<T>

I teach a weekly class on C# and .NET at my company to a group of procedural programmers, and every time I say something like “IEnumerable of T” I get back a bunch of blank stares. IEnumerable<T> is a generic interface that is implemented by every generic collection type in .NET. It is important to note that this is different from IEnumerator<T>, which we will not be implementing, at least not directly.

IEnumerable<T> is a pretty simple interface. In fact, it only exposes two methods, each called GetEnumerator() – one is generic and one is not. These methods return an IEnumerator<T>, which is just the default looping mechanism for the Collection. You’ll see this implemented in code later in this article.

For now, I want to stress that IEnumerable<T> is really what makes the magic of LINQ work. Anything that implements this interface (or one of its descendants) is queryable by LINQ. For a little terminology, we are going to use the term sequence to refer to anything that implements IEnumerable<T>. This is more accurate than Collection since there are Collections that do not implement this interface. So the answer to the question “When can I use LINQ to Objects?” is “You can use LINQ to Objects against any Sequence”.

Why use LINQ

So now that you know when you can use LINQ, lets talk about why using it is a good idea. Let’s revisit our old favorite, the Person class:

class Person
{
    public event EventHandler<maritalstatuschangedeventargs> MaritalStatusChangedEvent;
    private char _maritalStatus;

    public Person()
    {
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string DOB { get; set; }
    public bool IsMilitaryVeteran { get; set; }
    public char MaritalStatus
    {
        get
        {
            return _maritalStatus;
        }

        set
        {
            if (_maritalStatus != value)
            {
                _maritalStatus = value;
                if (MaritalStatusChangedEvent != null)
                {
                    MaritalStatusChangedEvent(this,
                        new MaritalStatusChangedEventArgs("Marital Status is now " + _maritalStatus));
                }
            }

        }
    }

    public string GetFullName()
    {
        return string.Format("{0}, {1}", LastName, FirstName);
    }

    public override string ToString()
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }
}

And let’s create a List of Person objects:

var people = new List<Person>()
    {new Person() {FirstName = "John", LastName = "Smith", DOB = "12/31/1968", IsMilitaryVeteran = true, MaritalStatus = 'M'},
     new Person() {FirstName = "Jimmy", LastName = "Crackcorn", DOB = "08/08/1934", IsMilitaryVeteran = true, MaritalStatus = 'S'},
     new Person() {FirstName = "Mary", LastName = "Contrary", DOB = "09/10/1957", IsMilitaryVeteran = false, MaritalStatus = 'D'}};

In a part 3 of this series on Lambda Expressions, we created a custom PersonCollection that inherited from List<Person> because we wanted to be able to filter these objects in specific ways. In that case, we were showing how to use a Lambda Expression with an Extension Method to loop through each Person that matched a certain Predicate<T> and perform some Action<T>. We initially did that by having the PersonCollection return another PersonCollection that was essentially a subset of the original. We could have also passed a more complex Lambda Expression that performed the filtering behavior for us as well as the Action.

In essence, though, the filtering done by the PersonCollection methods is a Query of the sequence. Rather than requiring a custom collection and predetermined methods, LINQ handles the query part for us. This buys us a couple of things. First, it means that we do not need a custom collection just to retrieve a filtered subset. Second, by not embedding this behavior in a Lambda Expression, we are substantively separating filtering behavior from actions on the filtered results. This means that both the filtering and the actions can be modularized.

Let’s look at an example:

var subset = from p in people
             where p.Age > 40
             select p;Console.WriteLine("Over 40:");

foreach (var person in subset)
{
    Console.WriteLine("{0} {1} is {2} years old. DOB: {3}", person.FirstName, person.LastName, person.Age, person.DOB);
}

If you compare these results to the list we created above, you’ll find that only the two over-40 objects are in the subset variable. This is what LINQ to Objects does for you: it allows you to query the Collection for a subset of objects. The resulting list is in fact an IEnumerable<T> for whatever type is in the Collection, so in this case we get back a list of Person objects. It also means I do not need access to the PersonCollection source code: I can execute LINQ statements over the collection directly, even if it is seaed, so I do not need to be able to create custom methods.

This is very powerful. Again, I’m not going to go over the mechanics of LINQ here, but suffice it to say that even this simple example should make you start to salivate. Imagine the possibilities! And it can be done with a very small amount of code.

Something more complex

As you may expect, the queries you write can be much more complex and functional:

var subset = from p in people
             where p.FirstName.StartsWith("J")
                && p.IsMilitaryVeteran
                && p.Age > 40
             select new {
                 LastName = p.LastName,
                 FirstName = p.FirstName,
                 Age = p.Age,
                 DOB = p.DOB
             };

There are some pretty cool things going on here that you need to be aware of. First, notice that I have complete access to all the members of the Person object in my query. Second, while a LINQ statement bears a strong resemblance to SQL, it is not SQL, so don’t judge it based on your SQL experience. Notably, it uses C# syntax and at first glance it appears backwards since the Select statement is last instead of first. This was done in order to support Intellisense, and Kathleen Dollard made a good point at a recent User group presentation: you may start to see SQL switch to this model (at least in the Microsoft World): wouldn’t it be nice to have full Intellisense support when writing SQL statements?

The third item of interest here is also in the Select statement. The first LINQ statement you saw returned an IEnumerable<Person>, but this one does not! In the select statement, we are actually creating an Anonymous Type by selecting only bits and pieces from our Person objects. In fact, these bits and pieces could come from multiple sources or be calculations or even new instances of complex types! This process of creating Anonymous Types from LINQ is known as Projection and it is very intriguing.

We discussed Anonymous Types and Compiler Inference in part 1 of this series, and now we see why they are so crucial. Without them, LINQ would be relegated to simply building subsets of Collections. With Projection though, LINQ becomes enormously powerful. Compiler Inference is used to create and build the Anonymous Type on the fly, and then is used again in order to loop through the newly created sequence. Without it, we would not be able to process the LINQ results, because in the case of projection there is no way to know the resulting Anonymous Type at design time.

Deferred Execution

I would be remiss if I did not at least point this out. A LINQ query is just a statement of execution: in other words, it is only a set of instructions concerning how to query a collection, it does not represent any data itself. No data is processed until the LINQ result object is referenced. This is called deferred execution, and you must be aware of it. If you do not understand this, “unpredictable results may occur”. Here is an example:

// Only define LINQ query - no data yet!
var subset = from p in people
             where p.FirstName.StartsWith("J")
                && p.IsMilitaryVeteran
                && p.Age > 40
             select new {
                 LastName = p.LastName,
                 FirstName = p.FirstName,
                 Age = p.Age,
                 DOB = p.DOB
             };
// "Subset" holds no data at this point

// Add new Person after LINQ query
people.Add(new Person() { FirstName = "Jill", LastName = "Upthehill", DOB = "12/31/1944", IsMilitaryVeteran = true, MaritalStatus = 'S' });Console.WriteLine("Over 40:");

// References LINQ query: NOW the data is gathered, so it includes the new Person
foreach (var person in subset)
{
    Console.WriteLine("{0} {1} is {2} years old. DOB: {3}", person.FirstName, person.LastName, person.Age, person.DOB);
}

Because the data itself is not read at LINQ definition time, it also means you can outsource the LINQ statements themselves to other classes and methods. Just be sure you return IEnumerable of Person:

public IEnumerable<Person> JVets(List<Person> people)
{
    var subset = from p in people
                 where p.FirstName.StartsWith("J")
                    && p.IsMilitaryVeteran
                    && p.Age > 40
                 select p;

    return subset;
}

Build your own Sequence

So far, we have been consuming known Sequences (such as List<Person>), but what if you wanted to perform LINQ over one of your own custom collection types? Hopefully by now the answer is obvious: you need to inherit from IEnumerable<T> or one of its children. The easiest way by far to do this is to inherit from one of the generic collections, such as List<T>. This would be my recommendation, but if you feel like getting into the nuts and bolts a little more, then you can implement IEnumerable<T> directly:

class PersonCollection : IEnumerable<Person>
{
    #region IEnumerable<Person> Members
    public IEnumerator<Person> GetEnumerator()
    {
        foreach (Person p in this)
        {
            yield return p;
        }
    }
#endregion

#region IEnumerable Members
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
#endregion
}

This is back to creating custom Iterators, which is beyond the scope of this article, but the magic here happens in yield return. This allows the collection to halt at each iteration and retain its position in the collection.

But here is the bad news: if you do this, you also have to implement all the Collection goodies, like Add(). This would be tedious and time consuming, and largely unnecessary since you could simply inherit from one of the Generic classes.

Conclusion

As stated at the beginning, this is not meant to be a LINQ primer. What you should get out of this is the following: you should use LINQ whenever you want to query collections. You can use LINQ to create collections of anonymous types, limiting the data and properties you have to deal with to just the ones you want. You can use LINQ to logically separate your queries from your actions.

And there is much more you can do with LINQ. You can aggregate results, join collections together, and so much more. Try it the next time you need to loop through a colleciton and pull out just certain objects. I think if you use it a couple of times you’ll find it becomes useful in a hurry.

Categories: .NET 3.5, C# 3.0, LINQ

Live Blogging RVNUG – December 2007

December 6, 2007 Comments off

Tonight I am visiting RVNUG (Roanoke Valley Dot Net Users Group) for the first time. Kathleen Dollard, a columnist for Visual Studio Magazine and author of Code Generation in Microsoft .NET (which I have and have read most of) is the featured presenter. She will be discussing “Refactoring with Generics”. How to make your code better with Generics, using Framework Generics, and how to use and make your own Generics.

Here are some bullets I garnered from the presentation:

  • Find out about the Converter<T> Generic Delegate.
  • “Team Test” is now part of VS2008.
  • Anonymous Delegates employ “Closure” – allows a private variable to be trucked off to (captured by) an out of scope method (like an anonymous delegate)
  • Return a LINQ list immediately by using “.ToList()”: no deferred execution
  • Format for declaring my own generics and specifying Type inheritance: public class GenericClass<TData, TCollection> : SomeBase where TCollection : List<TData> where TData : class

Conclusions

Overall, a good presentation. Unfortunately, it is a little dated when you consider all the new technologies out there. Kathleen did include some optional approaches using LINQ and Lambdas, but the bulk of the material is still 2.0 based. Don’t get me wrong: I’m not saying I didn’t learn anything because I did. I think I have a much better handle on creating my own generic classes now. But I think the target audience for this presentation should be developers moving from 1.1 to 2.0 or new developers.

Now for the scary part: the topic is very relevant. There are still an incredible number of people developing in pre-2.0 technologies who need this kind of information.

Kathleen is great: if you ever get a chance to go to a presentation of hers, by all means treat yourself: she really knows her stuff. We had a nice talk during dinner about the future of LINQ to SQL, OR/M, the Entity Data Model, and other Framework issues.? She was very patient with my questions and her answers reveal that she is one smart cookie.

Categories: .NET 3.5, C# 3.0

Upgrade your C# Skills part 3 – Lambda Expressions

December 5, 2007 28 comments

I’ve been very busy continuing my C# 3.0 and .NET 3.5 self-education. I’ve been focusing primarily on LINQ, but before I cover that here, which will take several postings, I wanted to cover Lambda Expressions. If you have been reading about LINQ and its related technologies at all, you’ve surely come across this term already. If you’ve already read some about Lambdas, then perhaps you came to the same conclusion I did: a lot of writers covering Lambda Expressions seem to want you to be boggled by them. In most articles, I found myself wading through a bunch of stuff I really did not need to know. In fact, it sometimes simply added more confusion.

So my goal in this article is to bypass all the pocket protector stuff and get right down to brass tacks. Here are a list of things I will NOT be covering that pervade almost every other article about Lambda Expressions:

  • Lambda calculus
  • Anonymous Methods
  • Functional Languages
  • Lexical Closures

If you are interested in any of the above, they are plenty of other articles out there. If, however, you are like me and just want to use this stuff, then read on…

Anonymous Methods

Before you scream foul, yes, I said I wasn’t going to discuss these, and really, I’m not. Or more accurately, I’m not going to explain them or show examples. You do have to know that Lambda Expressions are just another way to write Anonymous Methods. *whew*! Glad we got that out of the way!

The tricky part, though, for many programmers is knowing when to use Anonymous Methods. As far as our discussions go, it will be pretty easy: you want to use Anonymous Methods whenever you need to pass a method reference. This is done by use of delegates, something else I’m not really going to talk about.

So what you need to know is this: where ever you see a method that requires a delegate (or a reference to a method), you can use a Lambda Expression instead. An Anonymous Method is just a way to write the code for such a delegated method inline. So, we just need a way to know when we can use Lambda Expressions.

Actions, Predicates, and Funcs

What we need are Delegate Types. Delegate types are declared signatures for method calls that are used to wrap instance methods or, in our case, anonymous methods. Fortunately for us, there are some Generic Delegate Types built in to .NET that we can put to good use.

Action<T>

This is a Generic Delegate defined in .NET that will wrap and execute a method, passing it a variable of type T. Here is the MSDN Documentation. If you use this in a method declaration, you can actually pass a reference to a method, anonymous or otherwise, to a method of your own creation. For an example, check out this Extension Method:

public static void ExecuteOnValues<K, V>(this IDictionary<K, V> sequence, Action<V> action)
{
    if (sequence == null)
    {
        throw new ArgumentNullException("sequence");
    }

    foreach (var item in sequence.Values)
    {
        action(item);
    }
}

You can see here that our method signature expects a Generic Action<T> method reference. What we don’t know is what this method will do. The code line action(item) is saying “execute the method passed in on my action parameter, and pass it the item as a parameter.” So our Action method receives the Value of our Dictionary as a parameter and does something with it. We are going to use Lambda Expressions to define the “something”. Here is a simple example:

var dict = new Dictionary<int, string>();
dict.Add(1, "Coding");
dict.Add(2, "in");
dict.Add(3, "C#");
dict.Add(4, "Rules!");

dict.ExecuteOnValues(f => Console.WriteLine(f.ToString()));

Here we have created a new Dictionary<TKey, TValue> collection and added some data. Because Dictionary<TKey, TValue> inherits from IDictionary<TKey, TValue>, we can use our new Extension Method to execute some code against all the values in our Dictionary. But remember that our Extension Method really has no executing logic: it is expecting us to send it a reference or a delegate to it so it knows what to do. Enter the Lambda Expression. In the ExecuteOnValues method call above, f => Console.WriteLine(f.ToString()) is a Lambda Expression.

Anatomy of a Lambda Expression

// A simple Lambda expression
f => Console.WriteLine(f.ToString())

The “=>” thingy in the middle is the Lambda operator. This is what lets you know a Lambda is what is happening here. Let’s break the rest down into two parts: the left side and the right side. The left side represents a parameter list to be passed into the method. The right side represents the code the method will execute. Really, that’s it. You can make it harder if you want, but ultimately this is all it boils down to. Here is a diagram:

// A simple Lambda expression
f     =>    Console.WriteLine(f.ToString())
PARM Lambda CODE TO EXEUTE

So you can think of this as a method defined like so:

// A faux method representing a Lambda
void Method (unknownType f)
{
    Console.WriteLine(f.ToString());
}

In essence, without getting into all the pocket-protector details, this is what is the compiler is doing for you when it sees a Lambda Expression. The above is psuedo-code, and not entirely accurate, but you get the idea.

Where this gets confusing is that you really don’t see any type declarations, either for the parms or the return value. This is more Compiler Inference at work. In our example above, we specified that our Action generic was based on the Value Type of the Dictionary. The Compiler is able to look at the context of the Lambda Expression and simply infer that f is whatever type we specified on the Action parameter. You could write the details out, specifying the types, but not needing to is one of the major draws of Lambdas: the code is more compact and it “just works”. Now we’ll change our Dictionary to have a different Value type. We’ll make it our standard Person and add some people to it:

var dict2 = new Dictionary<int, Person>()
{
    {1, new Person() {FirstName = "John", LastName = "Smith", Age = 32, DOB = "12/31/1988"}},
    {2, new Person() {FirstName = "Jimmy", LastName = "Crackcorn", Age = 57, DOB = "08/08/1934"}},
    {3, new Person() {FirstName = "Mary", LastName = "Contrary", Age = 44, DOB = "09/10/2000"}}
};
dict2.ExecuteOnValues(f => Console.WriteLine("{0} is a {1} born on {2}", f, f.GetType().Name, f.DOB));

Now if we run this we’ll get these results (Click for full size image):

Person List
And now we get to see something else: in this Lambda, I am executing methods and Properties on my parameters. Pretty cool, huh?

So let’s read this Lambda out loud: “GIVEN f, EXECUTE {Console..WriteLine(“{0} is a {1} born on {2}”, f, f.GetType().Name, f.DOB));}”

Confused about the Looping? Don’t be: the loop is actually happening back in our Extension Method. All that’s happening here is that this code is executing (inside the loop) and using each Value from our Dictionary as the GIVEN parameter.

Predicate<T>

This is a Generic Delegate that evaluates a condition and returns true or false. Notice that Action<T> did not return any values. Predicate<T> is different because it returns a boolean value, and ultimately its only purpose is to determine whether or not a certain condition is met. Here is the MSDN documentation.

Let’s create a custom PersonCollection class and add a method that returns a sublist of Person objects who meet an unspecified criteria:

class PersonCollection : List<Person>
{
    public List<Person> MatchingPersons(Predicate<Person> condition)
    {
        List<Person> list = new List<Person>();

        foreach (Person p in this)
        {
            if (condition(p))
            {
                list.Add(p);
            }
        }

        return list;
    }
}

This code is specific to our PersonCollection class but still takes advantage of Predicate<T> to filter itself into a subsetted list. Let’s execute this now and get back just a list of Veterans:

var people = new PersonCollection()
    {new Person() {FirstName = "John", LastName = "Smith", Age = 32, DOB = "12/31/1988", IsMilitaryVeteran=true},
     new Person() {FirstName = "Jimmy", LastName = "Crackcorn", Age = 57, DOB = "08/08/1934", IsMilitaryVeteran=false},
     new Person() {FirstName = "Mary", LastName = "Contrary", Age = 44, DOB = "09/10/2000", IsMilitaryVeteran=true}};

Console.WriteLine("Print them all:");
people.ForEach<person>(f => Console.WriteLine("{0} is a {1} born on {2}", f, f.GetType().Name, f.DOB));
Console.WriteLine();

// Get a subset of people
var veterans = people.MatchingPersons(f => f.IsMilitaryVeteran);
Console.WriteLine("Print just veterans:");
veterans.ForEach<person>(f => Console.WriteLine("{0} is a {1} born on {2}", f, f.GetType().Name, f.DOB));

The beauty here is we did not specify what the criteria for the filtering was: we could have just as easily asked it for all the people whose first names begin with the letter “J”:

// Get another subset of FirstName beginning with "J"
var js = people.MatchingPersons(f => f.FirstName.StartsWith("J"));
Console.WriteLine("Print just Js:");
js.ForEach<person>(f => Console.WriteLine("{0} is a {1} born on {2}", f, f.GetType().Name, f.DOB));

Here is a screen shot of running all three of these in a row (Click for full size image):

Screenshot

Personally, I think this is a great tool, and the Lambda Expressions just make it that much more readable and easy to develop.

Func<T>

So far, we’ve seen Generic Delegates that return void and bool. That’s nice, and we can do a lot with them, but sometimes you need something more. This is where FUNC<T> comes in to play: it can return any type. In this case, the T is the return type. In the MSDN Documentation, they use “TResult” instead of “T”, so I’ll do that too. There are five Func Generic Delegates defined in .NET 3.5:

  • Func<TResult> – no parameters, returns type TResult
  • Func<T, TResult> – 1 parameter, returns type TResult
  • Func<T1, T2, TResult> – 2 parameters, returns type TResult
  • Func<T1, T2, T3, TResult> – 3 parameters, returns type TResult (are you noticing a pattern yet?)
  • Func<T1, T2, T3, T4, TResult> – 4 parameters, returns type TResult

What’s cool about Func is that you can create your own methods on the fly and give them meaningful names. Here is a simple example:

// Get a subset of people using Func
Func<Person, bool> isVeteranBeginsWithJ = f => f.IsMilitaryVeteran && f.FirstName.StartsWith("J");
Console.WriteLine("Print just veterans whose first name's begin with \"J\":");
foreach (Person p in people)
{
    if (isVeteranBeginsWithJ(p))
    {
        Console.WriteLine("{0} is a {1} born on {2}", p, p.GetType().Name, p.DOB);
    }
}

As you can see, I simply use my Func as any other method. I can see where this would come in very handy for short term reusability. Also, a lot of LINQ elements require Func delegates, so you have to have it in your toolkit.

Some odds and ends

There are a few items that I have to mention. First of all, Action<T> also has a few multiple parameter options:

  • Action<T1, T2>
  • Action<T1, T2, T3>
  • Action<T1, T2, T3, T4>

We did not discuss sending multiple parameters to a Lambda. To do so, wrap them in parentheses, like so:

// Example from Microsoft
(x, y) => x == y

While Compiler Inference is at work here, it is not required. If you wish to specify types for readability you can:

// Example from Microsoft
(int x, int y) => x == y

Calling a Lambda with no parameters, such as Func<TResult> is done with empty parentheses:

Func<string> getSomething = () => "Something";
Console.WriteLine(getSomething());

Lambdas can access local variables:

string todo = "To Do";
Func<string> getSomethingTodo = () => "Something " + todo;
Console.WriteLine(getSomethingTodo());

And Lambdas can be just as complex as you want them to be. Here is a Lambda that receives our custom PersonCollection and calculates the average age based on the DOB (if you’ve looked at the initializers, you’ll find that the Ages and the DOBs do not balance):

Func<PersonCollection, int> calculateAverageAge =
    (PersonCollection c) =>
    {   int totalAges = 0;
        foreach(var p in c)
        {
            string[] parts = p.DOB.Split(new char[] { '/' });
            int year = int.Parse(parts[2]);
            int calcAge = DateTime.Now.Year - year;
            totalAges += calcAge;
        }
        int averageAge = totalAges / people.Count;
        return averageAge;
    };

Console.WriteLine("Average Age of collection is {0}", calculateAverageAge(people));

And lots more. This is hardly the definitive article on Lambdas, but hopefully it explains enough to get you started. There is certainly enough background here to begin using Lambdas with LINQ, which will be next in this series of articles. Here is a link to the MSDN Lambda Expressions (C# Programming Guide).

Categories: .NET 3.5, C# 3.0

Making Automatic Properties Read Only

November 28, 2007 Comments off

In yesterday’s post, I included a blurb about Automatic Properties. Today, in my weekly C# class at my company, I was showing Automatic Properties to my students and I mentioned that you could not have a Read Only automatic property. To prove this, I removed the Setter from like so:

// This will not compile
public string FirstName { get; }

I then received a Compile error indicating that an Automatic Property must have both a getter and a setter. I was about to say that this proved my point when it dawned on me that I could try making the setter private, like so:

// Look, a Read Only Automatic Property!
public string FirstName { get; private set; }

Now this compiles just fine. I swear that at VSLive I saw someone try this and it failed, so either my memory is faulty or this was corrected before VS2008 went RTM. In either case, you can now implement an Automatic Property with a private Setter.

In my book, this is not truly Read Only, since the value can still be changed internally, but at least external consumers of the Property will not be able to alter its value, so I’ll still consider this a way to have a Read Only Automatic Property.

Categories: .NET 3.5, C# 3.0

Upgrade your C# Skills part 2 – Compiler Inference, Object Initializers, and Anonymous Types

November 27, 2007 7 comments

Well, that Title sure is a mouthful! “Compiler Inference”, “Object Initializers”, “Anonymous Types”: as fancy as these items sound, they are among some of the more mundane changes to C# 3.0. Don’t get me wrong: these changes lay the groundwork for all the really cool stuff going on in C#, especially LINQ. Truthfully, I should have covered these first, but I had actually been dreaming about Extension Methods, so I hope you’ll understand if I had to get that out of my system!

Compiler Inference

It probably isn’t fair for me to say this is “mundane”, but look at the two examples below:

// Old Way
Person p = new Person();
string name = p.LastName + " " + p.FirstName;

// New Way
var p = new Person();
var name = p.LastName + " " + p.FirstName;

Doesn’t seem like much, does it? All we did was replace the explicit Type with a new keyword called var. When you see var, what you are seeing is an instruction to the compiler to figure out for itself what Type the resulting variable will be. This is NOT var like in PHP or other loosely typed languages. Once assigned by the compiler, all the Strongly Typed rules still apply. And var can only be used for local variables, so it won’t be replacing all type references any time soon.

In the example above, “var p = new Person();”, the compiler will infer from the return type that variable “p” should be of type “Person”. Granted, in this simple example it doesn’t really mean much. It does mean less typing, especially when looping through generic collections, but where it will really come into play is with Anonymous Types and LINQ. In fact, without Compiler Inference, Anonymous Types could not function, but more on that later in the article.

There is some debate going on as to when to use Compiler Inference. Some feel that using var whenever possible is just lazy and leads to less readable code. These people think that you should use it only when it is really needed. In other words, if I know p is going to be a Person, then why not say so explicitly? Personally, I don’t have an opinion. I’ll use it when it seems convenient and of course where it is required. It certainly makes looping through Collections nicer to write:

// assume people is a List<Person>
foreach (var person in people)
{
    Console.WriteLine("{0} {1} is {2} years old.", person.FirstName, person.LastName, person.Age);
}

I have to think that if Person is later subclassed, fewer changes would be required to make this code continue to function. Is it lazy? Perhaps, but we all know that a good programmer is a lazy thief!

Object Initializers

Another cool feature are Object Initializers. Initializers allow you to set a series of Property variables when you create the object. How many times have you coded something like this:

Person p = new Person();
p.FirstName = "John";
p.LastName = "Smith";
p.Age = 32;

Now, you can shorten this considerably. Sort of like Array Initializers, which I’m sure we’ve all used, the syntax is a list of property=value pairs inside curly braces immediately following a constructor:

// You could, of course, use var here...
Person p = new Person() {FirstName = "John", LastName = "Smith", Age = 32};

An interesting side note about IntelliSense: naturally, inside the initializer block, IntelliSense will show you the list of properties available for the Person object. As you use Properties in the Initializer block, you will notice that they disappear from IntelliSense. This is a quick way to make sure you set every property (if you need to), and should help prevent listing duplicate properties (which, incidentally, throws a compiler error).

Now, for some extra coolness, you can embed Object Initialization inside a Collection’s Object Initializing block, so that this:

List<person> people = new List<person>();
Person p = new Person();
p.FirstName = "John";
p.LastName = "Smith";
p.Age = 32;
people.Add(p);

Person p2 = new Person()
p2.FirstName = "Jimmy";
p2.LastName = "Crackcorn";
p2.Age = 57;
people.Add(p2);

Person p3 = new Person();
p3.FirstName = "Mary";
p3.LastName = "Contrary";
p3.Age = 44;
people.Add(p3);

Can now be done like this:

var people = new List<person>()
    {new Person() {FirstName = "John", LastName = "Smith", Age = 32},
     new Person() {FirstName = "Jimmy", LastName = "Crackcorn", Age = 57},
     new Person() {FirstName = "Mary", LastName = "Contrary", Age = 44}};

As you can see, this is very concise and readable code. Less Typing = More Cool!

Automatic Properties

Since we are talking about properties, at least in a round about way, I want to throw in a quick item you may not be aware of called Automatic Properties. We all know that we are supposed to be exposing access to our variables via properties, but a lot of the time all we want to do is to be able to read and write the variable data. As such, we end up with a lot of code that looks like this:

private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value; }
}

Now, there is nothing wrong with this approach, but it feels a little verbose. To address this, you can now use an Automatic Property:

public string FirstName { get; set; }

The two main differences are that you do not define the variable, and you do not have to write the getter and setter logic. In fact, you’ll notice there aren’t even curly braces for get or set. The upside is that it is again less code for a common function. The downside is that you do not have an internal variable to access: you must use the Property name, even internally. Also, the Property must contain both the get and the set, so you cannot have a read-only Automatic Property. You also cannot add custom logic: get and set default behaviors are it.

The plus, though, is that if you start with an Automatic Property and need to add any of this functionality, you simply create the variable and update the Property as you would have before. There is nothing magic about Automatic Properties, this is just another example of the Compiler doing menial work for you. One last tidbit: in VS2008, if you use the “prop” code snippet, you will get the format of an Automatic Property by default. It really replaces the need for my Property Builder tool.

Anonymous Types

When I first learned about Anonymous Types, I didn’t think it would be all that big of a deal. The more I think about it though, the more I can see a use for it. And when I saw how they are used with LINQ, I was sold. Basically, you can define a Type without naming it or creating a separate class definition. Let’s revisit our Person and People class from before, only this time I am not going to define the Person Class:

var p1 = new {FirstName = "John", LastName = "Smith", Age = 32, FirstName="Harold"};
var p2 = new {FirstName = "Jimmy", LastName = "Crackcorn", Age = 57};
var p3 = new {FirstName = "Mary", LastName = "Contrary", Age = 44};

Here I have created three instances of my new Type, but I have not explicitly defined the type definition. Instead, the compiler has created a class for me and given it the Properties I listed (using our new friend, Compiler Inference). All of the properties are read-only, so once created, the values cannot be changed. Since the three objects above are all identical in their property names, all three objects are of the same (unknown) type. And IntelliSense still works as well: Typing “p1.” will reveal a list of the properties. I said earlier in the article that Anonymous Types could not function without Compiler Inference: hopefully it is obvious now what is happening above. “var” is the only option here, because the Type of the variable does not exist at design time. The Compiler must infer the Type to be of whatever class the Compiler creates, otherwise, you could not have Anonymous Types in a language like C# because of its strong typing.

Of course, there is a catch: as of yet, I have not figured out a way to use these in a list. You cannot use a Generic list, because there is no Type for strong typing. You can store them as Objects, but then you cannot cast them back out because there is no type. So what does this particular method buy you? In my opinion, not much. There could be an argument for using this method to replace the use of temporary Structs, a method I use frequently to store grouped information. But since I can’t store them in a list or pass these objects around, it would be a very limited approach.

There is, however, a necessary use for Anonymous Types: LINQ requires them to be able to create custom query results as a Collection. We’ll explore that more later this week, so be sure to check back.

Categories: .NET 3.5, C# 3.0, Visual Studio