Skip to main content

Introduction to Generic Methods in C#

When we create a method, class or interface, we usually specify the type of the parameter and its return type.
Ex.
Invoke the above function using
This will display 10 in the message box.
Now pass the string to the showValue function as shown below and you will get the compiler error “Invalid arguments” . That is because showValue function expects an integer and not a string;
To solve the problem what we do is write another overloaded functionshowValue which takes the string as input as shown below.
And invoke the above using the code
Now both will work fine.

Using Generics

In the above example we have duplicated the code MessageBox.Show(val.ToString()) in both the functions. This works correctly, but it is not efficient.  If we want to extend the function to handle double data type, then we need to write one more overloaded function repeating the code again.
The solution is to write the code once, which will handle all the types.  And that is where  generics come into the picture.
For Example the above code written in a generic way
And invoke the function using

Defining the Generic Method

Using Generics in C#
Using Generics in C#

What is  <T>

<T> is just a place holder for the data type.  It is more like a blueprint for the type.  is substituted by the actual type at the run time.
Instead of <T> you can use <X> and is perfectly valid

Multiple Parameters

Generic methods can have multiple parameters.
Parameters can be of different types. In the example below first parameter val1 is of a generic type, while second parameter val2 is of type int.

You can have two generic type parameters of different type as shown below.

Invoked as

Constraints on Parameters

We can specify the restrictions on the types of parameters using the whereclause.  A compile time error is generated when you call your generic method with the wrong types
For Example
Where T:struct
The Value type like int, float, struct etc. must be used as the parameter
and if invoked as

where T : class
Here reference type like string, class, arryays etc. must be used as the parameter. Example :
The Constrains for multiple generic types is as follows

Returning a Generic type from method

We can specify the return type from a generic method as follows


Generic Classes

Like methods classes can be made to act on generic types.  The concept is very much similar to the method.  In the example below,  we modified the code GenshowValue and moved it into the class.

And  invoked as

Generic Interfaces and delegates

The Interface and delegates can be made to use generic types similar to the class.

Advantageous of Using C# Generics

  • Allows you to write code which has the similar logic but can be applied to various data types. This enables you to reuse the code
  • Allows you to write type safe code as  C# Generics  are checked at the compile- time. If you use objects instead of generics, then casting to the correct type needs to be done at runtime.
  • Using objects instead of Generics also has problem of boxing/unboxing of value types or casting in case of reference types.

Conclusion

C# Generic programming allows us the create highly reusable code. Code that can be reused in many different places and situations.  Generics  allows us to create methods, classes, interfaces, and delegates work with multiple types while still being type safe.

Comments

  1. You understand your projects stand out of the crowd. There is something unique about them. It seems to me all of them are brilliant. SME Matching Grant

    ReplyDelete

Post a Comment

Popular posts from this blog

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API? ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including: Create resource-oriented services using the full features of HTTP Exposing services to a variety of clients easily like browsers or mobile devices, etc. What are the Advantages of Using ASP.NET Web API? Using ASP.NET Web API has a number of advantages, but core of the advantages are: It works the HTTP way using standard HTTP verbs like  GET ,  POST ,  PUT ,  DELETE , etc. for all CRUD operations Complete support for routing Response generated in JSON or XML format using  MediaTypeFormatter It has the ability to be hosted in IIS as well as self-host outside of IIS Supports Model binding and Validation Support for OD...

Extension methods in C#

Consider the class C# 1 2 3 4 5 6 7 8 9 10 11 12 13          namespace ExtensionMethod      {          public class testClass {              public string sayHello ( ) {              return "Hello" ;            }        }      }     Invoke the above from your form using C# 1 2 3 4 5 6          testClass test = new testClass ( ) ;      MessageBox . Show ( test . sayHello ( ) ) ;     This will show “Hello” in message box. Consider the scenario where you don...

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome...