Skip to main content
GameDev.net gamedev.net
🔒 Locked

Generic functions?

Started by Ezbez Sep 16, 2007 at 5:10 AM 5 replies 3.4k views
Original Post
Ezbez
Ezbez
Can you have a generic function that's not inside of a generic class in C#?
SiCrane
SiCrane
Yes.
Ezbez
Ezbez
Could you give a quick example of how? .NET Book Zero doesn't have any information about this that I can find.
SamLowry
SamLowry
Here a few ways the same thing (a map-function like in Scheme) can be achieved:
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) { ... }}

So, you just have to add your type parameters after the function name.

The AutoComplete feature of the IDE might be a bit annoying: if the return type does use the new type parameter (in this example, U), it will not know about this U yet as it is only introduced a little afterwards. Be careful that it does not produce List instead.
Ezbez
Ezbez
Thanks! How do you restrict the type of the type parameters with a 'where' statement?
SamLowry
SamLowry
Quote:
Original post by Ezbez
Thanks! How do you restrict the type of the type parameters with a 'where' statement?


Example for type parameters local to methods:
public void SortArray<T>(T[] array) where T : IComparable<T>{    SortArray(array, Comparable<T>.Default);}public void SortArray<T>(T[] array, IComparer<T> comparer){    ...}


Example on classes:
class Pool<T> where T : new (){    public void Alloc() { ... }    public void Free()  { ... }}


(BTW, pooling in java doesn't change much: I introduced pooling into a raytracer which was allocating new objects like crazy for the smallest things, but it didn't have a significant effect. I assume the same is true for C#)
Ezbez
Ezbez
Once again, thanks a bunch!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.