Bilal Itani Bilal Itani - 1 month ago 5
C# Question

How to return an object from an array with the same type of that item in C#?

I'm creating a sample method inspired by ruby's sample method that returns a random object from the array within bounds.

My method works fine, and I can call it like this:

questions.Sample<Question>();


And the function's source currently looks like this:

public static class ArrayUtils
{
public static T Sample<T>(this IList list)
{
var type = list[0].GetType();
return (T) list[UnityEngine.Random.Range(0, list.Count)];
}
}


So the problem is, rather than including the type that I want to return, I'd like it to just return the type of the objects in the array.

For example, if we have an array of type Question[], it should return an object of type Question.

Basically, in code, I want to change this:

questions.Sample<Question>();


To this:

questions.Sample();





Thanks for any help,

Bilal

Answer

You really only have 3 options.

Option 1 - you can do this if you really do not care about the type that is being returned. The result will always be returned as object.

public static object Sample(this IList list)
{
    return list[UnityEngine.Random.Range(0, list.Count)];
}

If you are using value types in your list boxing will occur when the result is returned as an object. Thanks for pointing that out @rory.ap

Option 2 - If you are using a generic IList<T> then you can do this in which case the generic specicier is copied from the parameter that is being used on.

public static T Sample<T>(this IList<T> list)
{
    return list[UnityEngine.Random.Range(0, list.Count)];
}

Option 3 - this is what you have already and you must specify the generic type.

public static T Sample<T>(this IList list)
{
    return (T)list[UnityEngine.Random.Range(0, list.Count)];
}