<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Use Reflectionto create an instance of the generic type specified using the parameters specified. Extension Method.</Title>
      <Shortcut>UseReflectiontocreateaninstanceofthegenerictypespecifiedusingtheparametersspecified.ExtensionMethod.</Shortcut>
      <Description>Use Reflectionto create an instance of the generic type specified using the parameters specified. Extension Method. [C#]</Description>
      <Author>John Tolar</Author>
      <HelpUrl>/PreviewSnippet.aspx?SnippetID=26e26328-1f07-4ffe-8d51-8f8a1a6c5339</HelpUrl>
      <SnippetTypes>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp"><![CDATA[/// <summary>
        /// Creates an instance of the generic type specified using the parameters
        /// specified.
        /// </summary>
        /// <typeparam name="T">The type to  instantiate.</typeparam>
        /// <param name="type">The System.Type being instantiated.</param>
        /// <param name="parameters">The array of parameters to use when calling  the constructor.</param>
        /// <returns>An instance of the specified type.</returns>
        /// <exception cref="System.Exception" />
        /// <remarks>
        /// If there is not a constructor that matches the parameters then an <see cref="System.Exception"/> is
        /// thrown.
        /// </remarks>
        /// <example>
        /// typeof(MyObject).CreateInstance(new object[] { 1, 3.0M, "Final Parameter" });
        /// </example>
        public static T CreateInstance<T>(this Type type, object[] parameters)
        {
            parameters.ExceptionIfNullOrEmpty("The parameters array must not be null.", "parameters");
            var ctor = type.GetConstructor(parameters.Select(parameter => parameter.IsNull() ? typeof (object) : parameter.GetType()).ToArray());
            if (ctor.IsNull())
            {
                throw new ArgumentException("There are no constructors for " +
                                            type.FullName + " that match the types provided.");
            }
            var result = (T) ctor.Invoke(parameters);
            return result;
        }]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>