Reputation: 1043
I have created an each helper like described here: http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx/
Now there is a bussiness rule when there is no items, create a dummy item so the loop gets executed once. Below the foreach statement I add the following:
if (!items.Any()) {
var result = template(new IndexedItem<T>(1, ???));
result.WriteTo(writer);
}
//Fixed by doing:
var result = template(new IndexedItem<T>(1, default(T)));
The questions marks I want to create a dummy object of type T, when searching I found Activator.CreateInstance() But im unable to get that working.
The question I have, first is this the best approach to resolve it, to have it executed once create a dummy object like suggesting above here. If so how would I create the dummy object then ?
Upvotes: 1
Views: 98
Reputation: 67898
One approach would be to use the new
constraint for T
here. So, for example, the class
or method
here that defines T
needs to add a constraint like this:
where T : new()
Please note that you must have a parameterless constructor on T
, and it cannot be abstract
:
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
Upvotes: 4