Saturday, November 8, 2014

Always choose generic type as return type of function.

It is good practice to choose Generic type as return type of function. The advantage is that we can return anything, which derived from the generic type. Let’s have a look on below example.

    public IEnumerable<string> Return()
            {
                List<string> data = new List<string> { "str1", "str2", "str3" };
                return data;

                string[] array = new string[] { "str1", "str2", "str3" };
                return array;

                ICollection<string> col = new List<string> { "str1", "str2", "str3" };
                return col;
            }

Here the return type of function is IEnumerable<string>. We know most of Collection implement this parameterized interface(IEnumerable<T>) and so that we can return those implemented collection when the return type is IEnumerable<T>.

In place of Ienumerable<T> we can return ICollection<T> too. Just like below example

    public ICollection<string> Return()
            {
                List<string> data = new List<string> { "str1", "str2", "str3" };
                return data;

                string[] array = new string[] { "str1", "str2", "str3" };
                return array;

                ICollection<string> col = new List<string>
 { "str1", "str2", "str3" };
                return col;
            }

In example, I have used multiple return statements in same scope, which is not meaningless programmatically but I wanted to just show that we can return many types when return type of function is generic type.
Anyway, we have seen example with collection of class library. The same is applicable in our own data type too. Let us see another example.

interface A
        { }

        class X : A
        {

        }
        class Y : A
        {

        }

        class Z
        {
            public A GetObject()
            {
                return new X(); // Return object of X class
                return new Y(); // Return object of Y class
            }
        }

The interface A is implemented in both X and Y concrete type. And when the return type of GerObject() method is A type we can return both object of X and Y.

So, it’s giving us more freedom in terms of return type.

No comments:

Post a Comment