Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading