Archive

Posts Tagged ‘Generic’

Anonymous Types and Generics

March 5th, 2009 No comments

C# 3.0 has a “nice” Feature called “Anonymous Types”.

Basically it is great for LINQ where you want to create a Type on the fly.
To create such a Type just use

var myAnonymousObject = new {
    Firstname = "John",
    Lastname = "Doe"
};

Now you possibly want to extend that a little and have a Function return a List of such a Type.
You can’t use List<T> because you don’t know the Type. You could use a List<object> but that’s not nice. It’s better to use a Feature called “Casting by Example”.

An Example Function implementing this Feature could look like:

public List<T> GetList<T>(T exampleObject)
{
    List<T> newList = new List<T>();
    // TODO: Fill the List somehow
    return newList;
}

You can then call this Function like this:

var someList = GetList(
    new {
        Firstname = "",
        Lastname = ""
    }
);
Ad

Better Type.GetMethod()

January 6th, 2009 1 comment

Getting a Generic MethodInfo with “Type.GetMethod()” is not really possible. That’s why I wrote this little Function which helps finding any Methods and return it’s correct MethodInfo on which you then can Invoke on. Read more…

Ad
Categories: C#, Programming Tags: , , ,