C# Indexers and how to use them

Indexers in C# are used quite a bit for collections, for example:


List<string> list = new List<string> { "a", "b", "c" };
string value = list[1]; // This is using an indexer

Dictionary<string, string> dictionary = new Dictionary<string, string>
{
    { "foo", "bar" },
    { "x", "y" }
};
string value = dictionary["x"]; // This is using an indexer

But how do you implement one for your own class? Have a look at my AddressBook class.


public class AddressBook
    {        
        private List<Address> Addresses;
        public int AddressBookSize { get { return Addresses.Count(); } }

        public Address this[int index]
        {
            get
            {
                return Addresses[index];
            }
            set
            {
                Addresses[index] = value;
            }
        }

        public AddressBook()
        {
            Addresses = GoToDatabaseOrServiceAndGetAddressList();
        }
    }

Notice how I create a public variable of type Address called this that exposes our private address list and gets and sets values to it. This is essentially an indexer.

Here is how I can use my AddressBook class making use of our indexer.


class Program
    {
        static void Main(string[] args)
        {
            var addressBook = new AddressBook();

            // use the indexer to update the address at index 2
            addressBook[2] = new Address()
            {
                HouseNumber = "X",
                HouseName = "Foo",
                Street = "Y Road",
                County = "Co.Z"
            };

            for (int i = 0; i < addressBook.AddressBookSize; i++)
            {
                // access address variables such as house number & name, you can even access functions this way
                Console.WriteLine("{0} {1}, {2}, {3}", 
                    addressBook[i].HouseNumber, 
                    addressBook[i].HouseName, 
                    addressBook[i].Street, 
                    addressBook[i].County);
            }

            // to keep console window open
            Console.ReadLine();
        }
    }

Source: Real world use cases for C# indexers?

Using delegates in C#

Ever been stumped by the question “What is a delegate?” and “How would you use them in your code?”. Here is an excellent explanation from Stack Overflow.

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that’s when you’ll need delegates.

The code below implements a simple console application to demonstrate this use of delegates. Notice how we pass the functions IsChild, IsAdult & IsSenior as parameters to the function DisplayPeople as the delegate type FilterDelegate.

namespace DelegateApp
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        // the delegate
        public delegate bool FilterDelegate(Person p);

        static void Main(string[] args)
        {
            // create 4 person objects
            var p1 = new Person() { Name = "Alan", Age = 26 };
            var p2 = new Person() { Name = "Jamie", Age = 69 };
            var p3 = new Person() { Name = "Dariaus", Age = 12 };
            var p4 = new Person() { Name = "Graham", Age = 41 };

            // create a list of person objects and fill it
            var people = new List<Person>() { p1, p2, p3, p4 };
            DisplayPeople("Childern:", people, IsChild); 
            DisplayPeople("Adults:", people, IsAdult);
            DisplayPeople("Seniors:", people, IsSenior);

            Console.Read();
        }

        static void DisplayPeople(string title, List<Person> people, FilterDelegate filter)
        {
            Console.WriteLine(title);

            foreach(var p in people)
            {
                if (filter(p))
                {
                    Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
                }
            }

            Console.Write("\n\n");
        }

        // These functions match the FilterDelegate delegate (They return bool and take a single parameter 'p' which is a person)
        // This means they can be passed as parameters into functions as a FilterDelegate
        static bool IsChild(Person p)
        {
            return p.Age <= 18;
        }

        static bool IsAdult(Person p)
        {
            return p.Age >= 18;
        }

        static bool IsSenior(Person p)
        {
            return p.Age >= 65;
        }
    }
}

I think this is a really nice and easy example of how to use delegates in C#.

Original source: when-why-to-use-delegates

Generate Random Color Object in C#

This is a handy little snippet if you’re stubbing out a UI and need to initialize color pickers, enjoy!

private Color GetRandomColor()
{
    Random randomGen = new Random();
    KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor));
    KnownColor randomColorName = names[randomGen.Next(names.Length)];
    Color randomColor = Color.FromKnownColor(randomColorName);
    return randomColor;
}

Source: How to generate random color names in C#