C# 3.0 Language Extensions

Put together a little snippet to remind myself of the some of the beautiful language extensions that shipped with the C# language.

namespace CSharpLanguageExperiment
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            // Object Initialiser
            Person bill = new Person { FirstName = "Bill", LastName = "Gates", Age = 40 };

            // Type Inference
            var ben = new Person { FirstName = "Ben", LastName = "Simmonds", Age = 25 };

            // Anonymous Types
            var john = new { FirstName = "John", LastName = "Smith", Age = 18 };

            // Anonymous Delegate
            Func filter1 = delegate(string name)
            {
                return name.Length > 4;
            };
            filter1("hel");

            // Lambda Expression
            Func filter2 = x => x.Length > 4;
            filter2("foobar");

            // Extension Method
            ben.GetData();

            // Queries
            List people = new List();
            people.Add(bill);
            people.Add(ben);
            Func filter = x => x.Age > 30;
            IEnumerable exp = people.Where(filter);

            foreach (Person person in exp)
            {
                Console.WriteLine(person.GetData());
            }
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

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

    // Extension Method
    public static class PersonExtension
    {
        public static string GetData(this Person person)
        {
            return String.Format("Name: {0} {1} Age: {2}",
                person.FirstName,
                person.LastName,
                person.Age);
        }
    }
}

BizTalk
Posted by: Ben Simmonds
Last revised: 28 Jun, 2011 01:17 PM

Comments

No comments yet. Be the first!

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview