Create a new instance of a object . - CSharp System.Reflection

CSharp examples for System.Reflection:Assembly

Description

Create a new instance of a object .

Demo Code


using System.Reflection;
using System.Linq;
using System.IO;//w ww. jav  a  2s  .com
using System.Collections.Generic;
using System;

public class Main{
        #region >> Static members

        /// <summary>
        /// Create a new instance of a <typeparamref name="T"/> object .
        /// </summary>
        /// <typeparam name="T">Type of object to be created.</typeparam>
        /// <param name="assemblyFileName">Path and filename to the assembly (if <c>null</c> or <c>Empty</c>, <paramref name="typeName"/> is supposed to be accessible.</param>
        /// <param name="typeName">Type name of the instance to create from the assembly.</param>
        /// <returns>A new instance of the <c>T</c> object, or <c>null</c> if the <paramref name="typeName"/> class could not be found.</returns>
        public static T CreateInstance<T>(string assemblyFileName, string typeName)
        {
            var instance = default(T);
            Type type;
            if (String.IsNullOrEmpty(assemblyFileName))
            {
                type = Type.GetType(typeName);
            }
            else
            {
                if (assemblyFileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                    assemblyFileName = Path.GetFileNameWithoutExtension(assemblyFileName);
                }
                var assembly = Assembly.Load(new AssemblyName(assemblyFileName));
                type = assembly.GetType(typeName);
            }
            if (type != null)
            {
                instance = (T)Activator.CreateInstance(type);
            }
            return instance;
        }
}

Related Tutorials