|
-
Apr 10th, 2006, 08:36 PM
#1
[2.0] Expense of Activator.CreateInstance
Is using Activator.CreateInstance an expensive operation? I happen to make it such that I would just pass the type of object then create an instance of it using the Activator.CreateInstance though I'm not quite sure of the drawbacks of using it if there is any...
-
Apr 11th, 2006, 03:39 AM
#2
Frenzied Member
Re: [2.0] Expense of Activator.CreateInstance
There is a certain performance impact above early binding/creation of objects. But nothing to be worried about (except if you are using this in a for() loop )
-
Apr 11th, 2006, 03:49 AM
#3
Re: [2.0] Expense of Activator.CreateInstance
I actually used it in my DAL Layer like (not sure with the correct syntax since I am air typing it)...
Code:
public class DataPortal<T>
{
...
public T FetchOne()
{
Type objectType = typeof(T);
object newObject = Activator.CreateInstance(objectType);
}
}
And sadly if I have to return a list of my business objects then I would really resort to looping...
It's being called in my BLL like...
Code:
public DataPortal<Employee> _dataPortal = new DataPortal<Employee>()
Employee is a business object class.
Is there any other way that I could achieve what I am doing instead of Activator.CreateInstance, a more efficient one?
-
Apr 11th, 2006, 01:35 PM
#4
Re: [2.0] Expense of Activator.CreateInstance
Is there a reason you prefer using the Activator over something like this:
Code:
// only allow T to be objects that are "newable"
public class DataPortal<T> where T : new()
{
// ...
public T FetchOne()
{
// which allows us to use ...
return new T();
}
}
Or, although I'm not sure on this and it might return null for classes,
Edit: yes, this will return null for T = a class, 0 for T = an integral type, and initialize the all members of a struct to either 0 or null when T = a struct. So maybe it's not that useful
Code:
public class DataPortal<T>
{
// ...
public T FetchOne()
{
return default(T);
}
}
Last edited by sunburnt; Apr 11th, 2006 at 04:29 PM.
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
-
Apr 11th, 2006, 10:16 PM
#5
Re: [2.0] Expense of Activator.CreateInstance
As for your...
Code:
public T FetchOne()
{
// which allows us to use ...
return new T();
}
I need to instantiate a T before actually returning it, do you have any other way?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|