Go to home page mail me! RSS Feed

Get a new instance of a generic object

Friday, April 17, 2009 5:24 PM

/// <summary>
/// using reflection to create an instance of a generic type
/// </summary>
/// <returns>T as the generic type</returns>
private static T GetNewObject()
{
    try
    {
        return (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });
    }
    catch {
        return default(T);
    }
}
 
/// <summary>
/// Create an instance of type T using the activator
/// </summary>
/// <returns></returns>
private static T GetNewInstance()
{
    return (T)Activator.CreateInstance<T>();
}

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 1 and 3 and type the answer here:

Preview Your Comment.

 
Next entries »