Original Post
Can you have a generic function that's not inside of a generic class in C#?
interface IFunction<T, U>{ U Eval(T t);}public delegate U Function<T, U>(T t);// Example of one parameter from class, one added locally for methodclass List<T>{ ... // Using interface public List Map(IFunction<T, U> func) { List result = new List(); foreach ( T t in lst ) result.Add( f.Eval( t ) ); return result; } // Using delegate public List Map<T, U>(List<T> lst, Function<T,U> f) { List result = new List(); foreach ( T t in lst ) result.Add( f(t) ); return result; }}public static class Util{ // Exact same syntax for non-static methods, just drop the static keyword public static List Map<T, U>(List<T> lst, Function<T, U> f) { ... }}Quote:
Original post by Ezbez
Thanks! How do you restrict the type of the type parameters with a 'where' statement?
public void SortArray<T>(T[] array) where T : IComparable<T>{ SortArray(array, Comparable<T>.Default);}public void SortArray<T>(T[] array, IComparer<T> comparer){ ...}class Pool<T> where T : new (){ public void Alloc() { ... } public void Free() { ... }}This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more