create a new instance of Object ?!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mironline
    New Member
    • May 2008
    • 24

    create a new instance of Object ?!

    dear friends
    I want to Create new instance of object with using Type with this code;


    Code:
    class Myclass(){}
    
    class OtherClass()
    {
    
    Myclass mc =  CreateNewInstance(typeof(MyClass));
    
    public ???? CreateNewInstance(Type e)
    {
     return // how can i create a new instance of Myclass here ? 
    }
    }

    is it possible to use this method o I have to find other solution .
    please help.


    ali.
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Well you can use the Reflection namespace to instanciate instances of objects, but I think the return value will be "object" and you would need to type-cast it

    Comment

    • PRR
      Recognized Expert Contributor
      • Dec 2007
      • 750

      #3
      Type Class is used for reflection purpose... Like at run time you want to compare object whether they belong to same base type or are objects of same type ... You cant return a Type and then cast it to another class object ...

      Comment

      • vekipeki
        Recognized Expert New Member
        • Nov 2007
        • 229

        #4
        You might want to take a look at Activator.Creat eInstance method.

        This should also work:

        Code:
        class OtherClass
        {
            public static T CreateInstance<T>() where T : new()
            {
                return new T();
            }
        }
        (if I understood correctly what you are asking for)

        In that case you would use it like this:

        Code:
        MyClass obj = OtherClass.CreateInstance<MyClass>();

        Comment

        Working...