Generic Type Instantiation in C#

by Donovan Olivier September 1, 2011 4:08PM

Most people know that you can get a Type object from a qualified string using the Type.GetType() method.  Let's say you have a class called MyClass in your MyAssembly assembly:

namespace MyAssembly
{
    public class MyClass
    {
        public MyClass() { }
        public string Name { get; set; }
    }
}

You can use the following call to get a System.Type instance for MyClass:

var type = System.Type.GetType("MyAssembly.MyClass,MyAssembly");

But what do you do if your class is defined with a generic type?  Let's say your class is defined like this:

namespace MyAssembly
{
    public class MyClass<T>
    {
        public MyClass() { }
        public string Name { get; set; }
        public T Data { get; set; }
    }
}

If you wanted an Type object for MyClass<string>, your natural instinct would be to try this:

var type = System.Type.GetType("MyAssembly.MyClass<string>,MyAssembly");

However, this won't work.  You need to specify the type using the following notation:

var type = System.Type.GetType("MyAssembly.MyClass`1[System.String],MyAssembly");

If your class has two generic types, like this:

namespace MyAssembly
{
    public class MyClass<T1, T2>
    {
        public MyClass() { }
        public string Name { get; set; }
        public T1 Data1 { get; set; }
        public T2 Data2 { get; set; }
    }
}

If you want MyClass<string, int>, the correct notation will now be:

var type = System.Type.GetType(
                      "MyAssembly.MyClass`2[[System.String],[System.Int32]],MyAssembly");

Tags: ,

Blog

'Between' Extension Method

by Donovan Olivier May 24, 2011 2:26PM

Check whether any IComparable<T> falls within a range.

public static bool Between<T>(this T item, T start, T end) where T : IComparable<T>
{
    return (item.CompareTo(start) >= 0 && item.CompareTo(end) <= 0);
}

Tags: ,

Blog

'In' Extension Method

by Donovan Olivier May 17, 2011 10:36AM

In the age old tradition of useless blog posts, here's an extension method that provides an alternate syntax for checking if an item is contained in a list:

public static bool In<T>(this T item, IEnumerable<T> list)
{
    return list.Contains(item);
}

Tags: ,

Blog

Validating South African ID Numbers

by Donovan Olivier August 25, 2010 11:56AM

I recently found a nice blog post explaining how to validate South Aftican 13-digit ID numbers, so here's my take on the code:

namespace Imaginary
{
    using System;
    using System.Linq;
    using System.Text;

    public enum Gender
    {
        Unknown,
        Male,
        Female
    }

    public class IdentityInfo
    {
        public IdentityInfo(string identityNumber)
        {
            this.Initialize(identityNumber);
        }

        public string IdentityNumber { get; private set; }

        public DateTime BirthDate { get; private set; }

        public Gender Gender { get; private set; }

        public bool IsSouthAfrican { get; private set; }

        public bool IsValid { get; private set; }

        private void Initialize(string identityNumber)
        {
            this.IdentityNumber = (identityNumber ?? string.Empty).Replace(" ", "");
            if (this.IdentityNumber.Length == 13)
            {
                var digits = new int[13];
                for (int i = 0; i < 13; i++)
                {
                    digits[i] = int.Parse(this.IdentityNumber.Substring(i, 1));
                }
                int control1 = digits.Where((v, i) => i % 2 == 0 && i < 12).Sum();
                string second = string.Empty;
                digits.Where((v, i) => i % 2 != 0 && i < 12).ToList().ForEach(v => 
                                                                 second += v.ToString());
                var string2 = (int.Parse(second) * 2).ToString();
                int control2 = 0;
                for (int i = 0; i < string2.Length; i++)
                {
                    control2 += int.Parse(string2.Substring(i, 1));
                }
                var control = (10 - ((control1 + control2) % 10)) % 10;
                if (digits[12] == control)
                {
                    this.BirthDate = DateTime.ParseExact(this.IdentityNumber
                                                       .Substring(0, 6), "yyMMdd", null);
                    this.Gender = digits[6] < 5 ? Gender.Female : Gender.Male;
                    this.IsSouthAfrican = digits[10] == 0;
                    this.IsValid = true;
                }
            }
        }
    }
}

To use it, simply instantiate a new IdentityInfo, passing in the ID number.


Tags: ,

Blog

How to Save/Restore Window Position

by Donovan Olivier June 6, 2010 8:14PM

Here's a small sample for saving and restoring window position in Windows Forms and WPF. It's using application settings to store the values and the .RestoreBounds property to get the window bounds if the window is currently minimized or maximized.

Save_and_Restore_Window_Position.7z (24.69 kb)


Tags: , , ,

Blog

BlogEngine.NET Twitter Widgets Updated

by Donovan Olivier May 10, 2010 9:02PM

Displaying the date published in the blogger's local time has been bugging me because it's probably quite meaningless to most of the readers. A quick Google search showed a couple of ways to display relative time (i.e. ‘an hour ago’ instead of an absolute time). I picked Jeff Atwood's method for stackoverflow.com with a couple of minor modifications. The relative time is a setting which is off by default in case you liked things as they were. Here are the updated Twitter widgets, bundled together.

Imaginary.Widgets.7z (6.30 kb)

UPDATE June 9, 2010: Incorporated feedback from JP Hellemons to correct an encoding issue in the feed widget.

UPDATE March 11, 2011: Ruslan Tur updated the widgets for BE2.0, you can grab them from here.


Tags: , , ,

Blog

BlogEngine.NET Twitter Feed Widget

by Donovan Olivier May 9, 2010 7:57PM

Continuing on from the Twitter search widget, I also created a feed widget. This lends heavily from the default BlogEngine.NET twitter widget, including Al Bsharah's changes.  The main implementation difference is that I've used .NET's System.ServiceModel.SyndicationFeed object to read the feed data instead of the System.Xml.XmlDocument used in the original.

Imaginary.TwitterFeed.7z (4.17 kb)

UPDATE May 10, 2010: Added relative time setting. Please grab newer version from here.


Tags: , , ,

Blog

BlogEngine.NET Twitter Search Widget

by Donovan Olivier May 5, 2010 7:27PM

I've created a Twitter search widget for BlogEngine.NET. This widget displays the results of a search rather than a specific user's tweets. What you're seeing here on my blog is the widget configured to search for ‘planetdonovan’. It's a bit of a challenge writing code for ASP.NET 2.0 when you've gotten used all the new C# language features, but you can still get everything done.

The source code is available for download here. If you make improvements or have fun using it, please let me know.

Imaginary.TwitterSearch.7z (4.18 kb)

UPDATE May 10, 2010: Added relative time setting. Please grab newer version from here.


Tags: , , ,

Blog

BlogEngine.NET Twitter Widget

by Donovan Olivier April 30, 2010 10:24PM

I have been using a modified version of the BlogEngine.NET Twitter widget that I got from Al Bsharah, but noticed that it doesn't correctly create the link for Twitter user names that contain an underscore.

An easy fix for this is to modify line 354 of his widget.ascx.cs file to include an underscore in the regular expression:

private static readonly Regex regex2 = new Regex("@[a-zA-Z0-9_]*", 
                                        RegexOptions.Compiled | RegexOptions.IgnoreCase);

UPDATE May 1, 2010: The original has now been updated.


Tags: ,

Blog

Unity 2.0

by Donovan Olivier April 21, 2010 6:07PM

So you've switched to Enterprise Library 5.0 and you're now finding compiler errors relating to generic implementations of .Resolve, .RegisterType, etc. in your UnityContainer? These are now extension methods, so just add the following to your class and your problem will be solved:

using Microsoft.Practices.Unity;

Tags: ,

Blog

Public Holidays

by Donovan Olivier April 9, 2010 11:29PM

I recently updated my component for calculating public holidays and have decided to share the C# source.  This is currently configured for South Africa, but can easily be updated to support any other country you choose (see the config file in the unit test project).

The standard holidays are stored in a custom configuration section as month and day, while easter is calculated for the specific year in question.  The provider determines if a public holiday falls on a Sunday and rolls it over to the Monday, as per South African standard (this behavior can be disabled in the configuration).

Enjoy. Any feedback would be appreciated.

Imaginary.Holidays.7z (12.70 kb)


Tags: , ,

Blog

The Perpetrator

perpetrator

Donovan Olivier

software developer, architect, husband, father, son, brother, uncle, nephew, sinistral, enquirer, skeptic, cynic, anarchist, contrarian, infidel, dissident, rebel, troublemaker, dissenter, renegade.