A little better, but to be honest your pretty much right on the button:
public object CreateNew(object obj)
{
Type t = obj.GetType();
ConstructorInfo ctorInfo = t.GetConstructor(type.EmptyTypes);
if( ctorInfo != null ) // better make sure there is a default ctor
return ctorInfo.Invoke(null);
else
return null;
}
Regards
Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog
nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<Og**************@TK2MSFTNGP11.phx.gbl>
Given an object on unknown type, I'd like to create a new
(default-constructed) object of the same type. After some playing with
Reflection (my first foray into that area), I came up with the following:
public object CreateNew(object obj)
{
Type t = obj.GetType();
ConstructorInfo ctorInfo = t.GetConstructor(new Type[0]);
return ctorInfo.Invoke(new object[0]);
}
Is there a better way?
--
Truth,
James Curran
Home:
www.noveltheory.com Work:
www.njtheater.com
Blog:
www.honestillusion.com Day Job:
www.partsearch.com
(note new day job!)
---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (
http://www.grisoft.com).
Version: 6.0.766 / Virus Database: 513 - Release Date: 17/09/2004
[microsoft.public.dotnet.languages.csharp]