dengkeli
dengkeli
CC#
Created by dengkeli on 10/4/2023 in #help
❔ Need guidance on generics, List, IEnumerable
So I have an implemented ECS in a game I'm working on. Admittedly I'm not the most seasoned c# programmer, but I believe I have gotten it to a state where it's usable and reasonably fast to do "queries" on. My question has to do with Returning generic lists. So with the following code has really been bugging me for a while:
public List<T> GetComponents<T>() where T : ECSComponent
{
Type componentType = typeof(T);
var componentList = components[componentType];
List<T> newList = new();
foreach (ECSComponent c in componentList)
{
newList.Add((T)c);
}
return newList;
}
public List<T> GetComponents<T>() where T : ECSComponent
{
Type componentType = typeof(T);
var componentList = components[componentType];
List<T> newList = new();
foreach (ECSComponent c in componentList)
{
newList.Add((T)c);
}
return newList;
}
This loop obviously sucks, but as I understand it and for good reason a cast here would be casting the list not the items and that's not possible. Cool. How about:
public List<T> GetComponents<T>() where T : ECSComponent
{
Type componentType = typeof(T);
var componentList = components[componentType];
var newList = componentList.Cast<T>().ToList();
return newList;
}
public List<T> GetComponents<T>() where T : ECSComponent
{
Type componentType = typeof(T);
var componentList = components[componentType];
var newList = componentList.Cast<T>().ToList();
return newList;
}
This seems better at a glace, but it seemed lest performant with large sets than just a foreach loop in the profiler. So I'm thinking "I don't need any of the List functionality of List on a return of this function I just need to be able to iterate and access the data. So why not return Just the IEnumerable.
public IEnumerable<T> GetComponents<T>() where T : ECSComponent
{
Type componentType = typeof(T);
CheckAddComponentList(componentType);
var componentList = components[componentType];
return componentList.Cast<T>();
}
public IEnumerable<T> GetComponents<T>() where T : ECSComponent
{
Type componentType = typeof(T);
CheckAddComponentList(componentType);
var componentList = components[componentType];
return componentList.Cast<T>();
}
Seems even better right?
28 replies