[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

why i need Activator CreateInstance?

Posted on 2011-04-25
2
Medium Priority
?
469 Views
Last Modified: 2012-05-11
Why i need Activator CreateInstance? i don't need to use create new instance via Activator createInstance can you explain why i need Activator. can you give some advise when i need to use activator.CreateInstance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace App.CreateInstance
{
    class Program
    {
        static void Main(string[] args)
        {

            new MyCustomerManager().Save <MyCustomer>(new object[] { 1, "xxx", "yyyy" });
        }
    }

    public class MyCustomerManager
    {
        public void Save<TModel>(object[] Vals)
        {
            Type calcType = typeof(TModel);
            object instance = Activator.CreateInstance(calcType);
            PropertyInfo[] ColumnNames = instance.GetType().GetProperties();

            for (int i = 0; i < ColumnNames.Length; i++)
            {
                calcType.GetProperty(ColumnNames[i].Name, BindingFlags.Instance | BindingFlags.Public).SetValue(instance, Vals[i], null);
            }

            string result = "";
            for (int i = 0; i < ColumnNames.Length; i++)
            {
                result += String.Format("{0}:{1}", ColumnNames[i].Name, calcType.GetProperty(ColumnNames[i].Name,
                                        BindingFlags.Instance | BindingFlags.Public).GetValue(instance, null).ToString());
            }
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

    // Model
    public class MyCustomer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }
}

Open in new window

i can do that without Activator.CreateInstance:

using System.Reflection;

namespace App.ReflectionToGeneric4
{
    class Program
    {
        static void Main(string[] args)
        {
            object[] Vals = new object[] { 1, "xxx","yyyy" };
            new MyCustomerManager().Save<MyCustomer>(Vals);
        }
    }

    // Model
    public class MyCustomer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }

    public class MyCustomerManager
    {
        public void Save<TModel>(object[] Vals) where TModel : class, new()
        {
            var instance = new TModel();
            Type calcType = instance.GetType();
            PropertyInfo[] ColumnNames = calcType.GetProperties();

            for (int i = 0; i < ColumnNames.Length; i++)
            {
                  calcType.GetProperty(ColumnNames[i].Name,BindingFlags.Instance|BindingFlags.Public).SetValue(instance, Vals[i], null);
            }
            string result = "";
            for (int i = 0; i < ColumnNames.Length; i++)
            {
                result += String.Format("{0}:{1}", ColumnNames[i].Name, calcType.GetProperty(ColumnNames[i].Name, 
                                        BindingFlags.Instance | BindingFlags.Public).GetValue(instance, null).ToString());
            }
            Console.WriteLine(result);
            Console.ReadKey();

        }
    }
}

Open in new window

why i need create Instance? Can you show me?
0
Comment
Question by:programmerist
  • 2
2 Comments
 
LVL 11

Expert Comment

by:saragani
ID: 35459691
Hi, in this case you don't need the Activator...
You should better have this:

public void Save<TModel>(object[] Vals) where TModel : new()


This way you can also have value types (like int) as the TModel.
0
 
LVL 11

Accepted Solution

by:
saragani earned 2000 total points
ID: 35459857
You will probably need the activator in cases where the function is not generic (For example, you get a type or an instance and you need to create a new one).
I use it in MEF, but there are plenty more situation where you can use it.

You can also use it if the parameter-less constructor is private (Which will not work with the new() trick):

 TModel instance = (TModel)Activator.CreateInstance(typeof(TModel), true);


The activator can also be called with:
 TModel instance = (TModel)Activator.CreateInstance(typeof(TModel), params);
(where params is array of objects).

This way you can call a non-parameterless constructor.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question