Creating a new object of a GetType() type throws an exception. Why?

  • Thread starter Thread starter Paul Jones
  • Start date Start date
P

Paul Jones

Hi,
I need to create a new object of the same type as another variable is.
Since I do not know the exact type (it varies within the function), I
need to get the original type using GetType(). I've found somewhere on
the internet that the new variable can be created this way:

Object celldata = row.ItemArray.GetValue(i);
Object newobj = Activator.CreateInstance(celldata.GetType());

The second line throws an exception "A constructor without parameters is
not defined for this object." Why? celldata is typed as string at this
moment...

Thanks for any help...

With regards
Paul Jones
 
Paul Jones said:
I need to create a new object of the same type as another variable is.
Since I do not know the exact type (it varies within the function), I
need to get the original type using GetType(). I've found somewhere on
the internet that the new variable can be created this way:

Object celldata = row.ItemArray.GetValue(i);
Object newobj = Activator.CreateInstance(celldata.GetType());

The second line throws an exception "A constructor without parameters is
not defined for this object." Why? celldata is typed as string at this
moment...

Thanks for any help...

I see your name there 'lazy paul j'. I don't want to encourage laziness,
so I'll point out just two things:

* The exception is saying that there's no constructor without
parameters.

* You say celldata is typed as string - that's equivalent to
System.String.

I suggest you look in the documentation for System.String and examine
its constructors.

-- Barry
 
Hi Barry, I guess I should change the e-mail address... :)

Well, as I found out after I posted the question there really is no
string constructor with no parameters, but I was not able to figure out
how to give those parameters to the constructor... Nevertheless, after a
thorough examination of CreateInstance overloads' parameters it was
quite clear...

Thanks for the advice, I think this approach is sometimes better than
providing a complete solution... :)

With regards
Paul Jones


Barry Kelly napsal(a):
 
Back
Top