Monday, February 14, 2011

Generic Functions

In general Generic function provide us facility to

1. create such a function whose return type we can decide while making call to that function.

let say i wants to create a function which takes a string and return me that value to be converted in any other type. like i pass any string value and i wants it to be returned as a int/date/any other type.

public T GetValue(string value)
     return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
call it like:
int x = GetValue("1234");
in above call we are setting that we wants the result of "GetValue" function as a "int" so i called it like "GetValue".

2. we can create such function whose parameter's datatype can be decide while making call to that function.

eg. i wants to create a function which can be used to swap values of two variables and the variables can be of any datatype means i can pass int/float/string/date.
so to do earlier we was to create lots of overloaded function. means 1 function for each supported datatype.
but we can do it easily just by writing a single function as a generic function.
static void Swap(ref T lhs, ref T rhs)
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
you can call it like:
Swap(ref a, ref b);
even it provides you more flexibility like you can also omit the type argument and the compiler will infer it. The following call to Swap is equivalent to the previous call:
Swap(ref a, ref b);

Definition:Generic functions are functions declared with a generic type parameter. They may be methods in a class or struct, or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.

When called, the generic type parameter is replaced by an actual type. The actual type may be explicitly specified in angled brackets using syntax similar to a template function call. If called without the type parameters, the compiler will attempt to deduce the actual type from the parameters supplied in the function call. If the intended type argument cannot be deduced from the parameters used, the compiler will report an error.


Solution By: Rajesh Rolen

Share This!

No comments:

Powered By Blogger · Designed By Seo Blogger Templates