I was wondering if there's a more generic way of handling the creation of new Objects without needing to know the exact Object Type.
If I have two simple Object Types as
class TemplateA {
public string field01;
public string field02;
public TemplateA(List<string> values) {
this.field01 = values[0];
this.field02 = values[1];
}
}
class TemplateB {
public string field01;
public string field02;
public string field03;
public TemplateB(List<string> values) {
this.field01 = values[0];
this.field02 = values[1];
this.field03 = values[2];
}
}
Then I can use a function with a Generic Type that just takes a List of Lists and changes the Constructer it calls
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<List<string>> rows;
rows = new List<List<string>>{
new List<string> {"Row01_Field01", "Row01_Field02", "Row01_Field03", "Row01_Field04"},
new List<string> {"Row02_Field01", "Row02_Field02", "Row02_Field03", "Row02_Field04"},
new List<string> {"Row03_Field01", "Row03_Field02", "Row03_Field03", "Row03_Field04"}
};
List<TemplateA> itemsA = PopulateItems<TemplateA>(rows);
List<TemplateB> itemsB = PopulateItems<TemplateB>(rows);
}
public static List<T> PopulateItems<T>(List<List<string>> rows) {
List<T> items = new List<T>();
foreach(List<string> row in rows) {
T item = default(T);
if(typeof(T) == typeof(TemplateA)) { item = (T)(object)new TemplateA(row); }
if(typeof(T) == typeof(TemplateB)) { item = (T)(object)new TemplateB(row); }
items.Add(item);
}
return items;
}
}
This seems a bit clumsy though because every time a new Template gets added, a new type check will need to be added to the PopulateItems function.
I was wondering if there's a way to handle the creation of the new Object in a generic way to bypass the need for manual type checking
You can try using Activator.CreateInstance
class:
public static List<T> PopulateItems<T>(List<List<string>> rows)
{
List<T> items = new List<T>();
foreach (List<string> row in rows)
{
T item = (T)Activator.CreateInstance(typeof(T), row);
items.Add(item);
}
return items;
}
This approach removes the need for manual type checking and allows you to create new template classes without modifying the PopulateItems method. Just know that using reflection can be slower than using regular method calls, so if performance is a super* concern, then this might not be the right method.