[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...
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 :))
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?
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);
}
}
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? :)