How to create a new object.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

string typename = obj.GetType().FullName;
where obj is a object of any type.

Now my problem is how to create back the object just by passing this typename.

Thanks for the help.

Best Regards,
 
In the reflection Namespace there's a calls called Activator. On that
class you use the method CreateInstance
 
Thank you. But I have FullName of the Type not the assembly. In Activator
class I need to pass either Type or FullName of the assembly.
So How to do this?



Patrik Löwendahl said:
In the reflection Namespace there's a calls called Activator. On that
class you use the method CreateInstance


--
Patrik Löwendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'
Hello,

string typename = obj.GetType().FullName;
where obj is a object of any type.

Now my problem is how to create back the object just by passing this typename.

Thanks for the help.

Best Regards,
 
You have the full name of the type, but you don't know what assembly its in? If thats the case then you are stuck, consider this code

Assembly 1
namespace Richard
{
class Hello
{
public void Foo()
{
}
}
}

Assembly 2
namespace Richard
{
class Hello
{
public void Bar()
{
}
}
}

now I write the code in my application assembly

Activator.CreateInstance(Type.GetType("Richard.Hello));

So the question is, which class is it meant to create, the one from assembly 1 or the one from assembly 2? Thats why you need the assembly name.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Thank you. But I have FullName of the Type not the assembly. In Activator
class I need to pass either Type or FullName of the assembly.
So How to do this?
 
Hello,
Thank you. My first option was to store the type itself. But I coudnt
Serilaize the object which has a public field of type System.Type. I was
getting the exception with Messgae" There was an error reflecting type
classname". If I store the fullName instead of Type itself it worked fine.
Will loading all the assemblies before trying to create the object cause any
performance issues?

Gana.

James Curran said:
gana said:
Thank you. But I have FullName of the Type not the assembly. In Activator
class I need to pass either Type or FullName of the assembly.
So How to do this?

So, don't save just the name--- Save the Type.

--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
 
Back
Top