method that returns a component of a specified Type

I try to make a method that returns a component of a specified Type and just cant figure it out.

The components are things like meshes etc. that derive from a Component class.
I have an array of components called "components".

public unsafe T GetComponent<T>()
        {
            T t = default(T);
            foreach (Component component in components)
            {
                if (component.GetType() == typeof(T)) t = (t.GetType())component;
            }
            Console.WriteLine("component not found: "+typeof(T).Name);

            return t;
        }

enter image description here

>Solution :

It looks like you are trying to load a default based on type. I’d use a dictionary instead of a list of components and use the type as your key. Make it a ConcurrentDictionary<Type, Component> if there are multiple threads looking at the data.

Assuming you’ve already populated the dictionary, it would look something like this:

public T GetComponent<T>()
{
  // var components is IDictionary<Type, Component>
  return components.TryGetValue(typeof(T), out var result)
    ? result as T
    : default(T);
}

You can also store a Func as the dictionary value and use it as a basic value factory. This is especially useful if you want a new instance of T each time you call the function, instead of sharing instances like you would with the first solution.

public T GetComponent<T>()
{
  // var components is IDictionary<Type, Func<Component>>
  return components.TryGetValue(typeof(T), out var result)
    ? result() as T
    : default(T);
}

Also, be careful of keywords like unsafe. You really don’t want to use those unless you specifically need them, ie you’re working with pointers directly and not variables.

Leave a Reply