Hello ppl... Can someone show me how to make a method with "unknown" data type ?

I want to create one function for sorting array with different data type...
(I know for .NET library but I want to create custom library...)

For example:

public class Sort
    {
        // THis function is only for int[] data type
        // I want this function to be for all (numerics) data types
        private static int[] bySmellest(int[] Arr)
        {
            for (int i = 0; i < Arr.Length; i++)
            {
                for (int j = 0; j < Arr.Length; j++)
                {
                    if (Arr[j] < Arr[j - 1])
                    {
                        int tmp = Arr[j];
                        Arr[j] = Arr[j - 1];
                        Arr[j - 1] = Arr[j];
                    }
                }
            }
            return Arr;
        }

        // Error - byte[] != int
        public static byte[] BySmallest(byte[] Arr)
        {
            return bySmellest(Arr);
        }

        // Error - short[] != int
        public static short[] BySmallest(short[] Arr)
        {
            return bySmellest(Arr);
        }

        // True - int[] = int[]
        public static int[] BySmallest(int[] Arr)
        {
            return bySmellest(Arr);
        }
}

Thanks...

Recommended Answers

All 2 Replies

Is this along the lines of what you are looking for? If so there are tons of resources about generics out there.

This functionality already exists and why not implement sort for every data type that supports IComparable or IComparable<T> ? There are extension methods in LINQ for dealing with arrays. You can call .ToList() on the array, move it to a list, and sort that. Or you could sort the array in place:

int[] somearray = new int[5];
      Array.Sort(somearray);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.