Archives

Archives / 2008 / May
  • ParseChildren in Templated Controls

    Well, I have been spending sometime learning about Templated controls at work. Hence I am slowly getting an understanding of common attributes that you would want to use on Templated controls. If your template control inherits from WebControl than you do not need to worry about setting ParseChildren to true because by default WebControls have ParseChildren set to true. However if your controls inherit from Control class, than in order to get Templates to work you need to set ParseChildren to true. When you set ParseChildren to true, asp.net parser maps the top level tags of the server control to properties on the server control. For e.g

  • Instantiating Templates

    I thought to write a blog post telling what is the correct way to instantiate templates because on researching many blog posts and reading few articles, I saw couple of different usages and one of them is misleading and incorrect. Here is the most common way of instantiating templates for a custom control.

  • Use TemplateInstance.Single to avoid FindControls

    If you have created templated controls, you would be aware that it requires you to implement INamingContainer. Only job of INamingContainer is to ensure that controls are unique within that Naming Container. However sometimes if you are using Templated controls that are not going to be repeated like LoginView Control has anonymous Template which does not have a concept of a repeated template, in those cases you would like to be able to access those controls directly in the page.Templated controls have a requirement that contents with in the templated controls must be instantiated inside of a container that implements INamingContainer. Here is a simple example that illustrates this behavior.

  • When to instantiate templates

    Most of the examples that I saw on the net recommended to instantiate templates inside of CreateChildControls method but it does not work correctly. Basically I marked my Itemplate property to TemplateInstance.Single, so all the controls inside my template are available to the page without using FindControl. This works great but only in design time. In the design mode, I can access all the controls but when the page executes, any controls being accessed that are inside of template causes object reference not set to an instance of an object. For a while I couldn't figure out what was going on. Then I realized that UpdatePanel has pretty much the same implementation I can access all the controls inside of UpdatePanel without any problems. Using Reflector I saw that UpdatePanel was not instantiating the template inside of CreateChildControls, in fact they were instantiating the template inside ITemplate property as shown below

  • Using Pragma to disable warnings

    Lot of times, you have variables declared in your class that are never getting used directly and are accessed and their values altered using reflection. In those cases when you build you solution you get a warning saying that this particular field is never used. Here is a simple example that shows warning for first field in Person class for not being used.

  • Global Namespace in C#

    By default if you do not specify a namespace for a class it will go to default namespace. What happens When you are in particular namespace that has the same class that is also available in default namespace. How do you access the class that is available in default namespace. With C# 2.0, global keyword was introduced which allows you to access class that is available in global namespace. Here is an example that illustrates the problem and how we use global to access class available in global namespace.

  • Callbacks in Asp.net Ajax

    Callbacks provide an ability to call a function passing in additional parameters that your function would need. In the past to achieve this objective, I have created global variables that can be referenced from any where in your code. . Instead using callbacks, you can pass in a context that has the information your function would need. In the example below, I am passing an array of numbers to a callback function which simply writes the array to a label. Here is the markup

  • Moving Divs on the page

    Today I had a need to move my progress bar control on top of any control that was being updated asynchronously. Therefore I had to reposition my progress bar when an update happened. This lead me to investigate asp.net Ajax client side library and see what api it provides me to move a div from one position to another on a page. Sure enough Sys.UI.DomElement provides a method called getbounds which returns the width,height, x and y coordinate of an element on a page. The DomElement object also provides static method called SetLocation that takes 3 parameters. First parameter is the element that you want to move. Second and third parameters specifies the x and y coordinate of the location where the element should be moved to. To demonstrate the usage I have created a simple page which has 2 buttons. First button simply returns width, height,x and y coordinate of an element on the page. Clicking the second button moves the div to new x and y location on the page. X and Y positions are obtained as user input from the textboxes on the page. Here is how the page looks like.

  • Prevent Enter Key using Asp.net Ajax

    Today at work, I had a requirement where I had to prevent user from pressing enter key when they are on a particular textbox because it would cause the page to postback which I wanted to prevent. Using asp.net Ajax, you can register for the keypress event. The key press event gets an argument of type Sys.UI.DomEvent. The DomEvent object has a property called charCode which tells you which key the user has pressed.You can compare the charCode value with Sys.UI.Key.enter to check if the user has pressed enter key. On confirmation that user has pressed enter key, I make use of method exposed on DomEvent class called preventDefault. PreventDefault basically prevents the default action from happening which in my case prevents the enter key from being executed. Here is the code that prevents enter key from being executed by trapping keypress event on textbox.

  • Debug Vs Release Version of JavaScript file

    When you are debugging application it is easier to work with debug version of js file because the code is indented and comments provide better readability. However when deploying it production debugs version would increase the load time of the page. ScriptManager makes it really easy to work with debug and release versions of JavaScript file by using its ScriptMode property. For instance if you are referencing a JavaScript file called Popup.js, in order to get debug and release support from ScriptManager, you need to have two versions of the the js file like Popup.js and Popup.debug.js and depending on the ScriptMode set on the ScriptManager it will pull the appropriate JavaScript file. Here is an example that shows how to reference debug and release version of a JavaScript file.

  • Getting Intellisense in External JavaScript files

    If you are having problems getting Intellisense to work in external JavaScript file, you need to add reference directive with 3 /// comments. If you are pointing to your copy of js file, use Path attribute otherwise use name attribute to reference any JavaScript files outputted by the script manager. Here is the syntax for referencing both kinds of JavaScript file.

  • Authentication and Profile Services in asp.net Ajax

    With .net 3.5 Microsoft introduced authentication and profile services which allows you to authenticate using client side libraries. You also have the ability to update values in your profile using asp.net profile services. To work with this example, you need to set to up Membership ship database by using aspnet_regsql command. Enable form based authentication by changing the authentication mode to Forms. If you have created asp.net 3.5 website project, you will see profile and authentication and role service registered in config section of web.config as follows.

  • Getting entire XML content

    Another hidden jewel in the new XML api is the ToString method. ToString method has been overwritten in XElement. In Dom W3C api if you were to do ToString, you would end up with object type. However ToString in XElement outputs the XML string itself. It is nice to be able to pull a certain fragment of XML once you have obtained the reference to a particular XElement. Here is a simple example that illustrates the nice feature.

  • Getting Node Value using XElement

    If you have used Xml api in previous versions of C#, you must have felt the pain to extract node value and cast it to the correct type. With C# 3.0 new xml api, getting Node value is as simple as casting the node to the right type. You can still use the old fashioned XmlConvert class and convert the value to the right type by passing in the Value property of the node to get to the node value. Here is an example that illustrates how easy it is to convert xml node value to the right type.

  • Using AsEnumerable Hint

    Recently I had a huge query that I wanted to execute on SQL server. However certain portion of query had to be executed in C# as linq to objects because SQL server cannot comprehend regular expression. In trying to figure how I can tell linq to SQL to not execute this portion of the query in SQL server, I discovered AsEnumerable operator. AsEnumerable operator is a hint that tells linq to SQL to execute the portion following it in memory. Here is an example of a query that gets the data for customers from SQL server but applied a regular expression filter in memory. It is not the best solution but illustrates how you can use these hints to drive what gets executed on SQL server.

  • Associations To Joins in LINQ TO SQL

    When your SQL server tables has foreign and primary keys constraint defined, dragging those tables on the linq to SQL designer creates association relationship that can help traverse other related objects. For instance, if you have an order table than you may want to traverse the customer for that order and as well as find out the employee who submitted the order. When you are using the dot operator to do the traversal, linq to SQL uses different join based on the schema defined for the relationship. Let's look at a couple of different traversal to understand what kind of query gets sent to SQL server.

  • Filtering LINQ To SQL using Object comparison

    One of the recent trick I discovered with linq to SQL queries is, when you want to filter records, you do not necessarily have to filter by primary key like CustomerID. Instead you can compare object references and linq to SQL in the background would convert the linq query as comparison based on primary key of that table. For instance if I want to find all the orders for a particular customer, I would write a query like this

  • Handling errors in asp.net Ajax

    The default configuration for asp.net Ajax simply shows an alert box if your asynchronous postback causes an exception. This may not be the appropriate way you want to handle exceptions in your application. Here is a simple markup that illustrates this behavior.

  • Refreshing the page on Interval basis

    If you ever wanted to refresh a portion of your page on a certain interval, it does not get any easier with asp.net Ajax. Simply surround the content with an Update Panel and trigger the update of the Update Panel using the timer control. Here is the markup that illustrates this example.

  • Order of Where Clause Matters in Linq To Objects.

    The order in which you apply where and join in SQL server does not matter too much. One of the reason is that SQL server has its own optimizer built in which knows how to rewrite the query so it is optimized for best performance. However we don' get that luxury with Linq to objects. Therefore it is essential that you understand how to write your query so that it gives you maximum efficiency. For instance apply your filter before joining because filtering would reduce the number of rows returned and as a result there would be fewer rows that you would need to join against. Here is a simple example that illustrates the performance gain that you would get when you apply the where clause before the join statement.

  • Optimizing join queries in Linq to Objects.

    For many years working in SQL server environment and writing dozens of joins, I never cared which table needs to come first and which one comes second. The reason was SQL server would use table statistics to determine best way to join two tables. However we don't get this luxury when we are writing Linq to object queries in C# 3.0. For instance if you have two sequences in memory and you have to join those two sequences, than always use the smaller sequence on the right side of your query and the larger sequence on the left side. It makes a considerable difference in performance. To prove that there is a big difference in the time it takes for the query to execute I will put a small sequence on the right side and run the query to see how long it takes.

  • Order in join clause matters in Linq

    Yesterday I was writing a Linq query that required joining two tables and mistakenly reversed the order of columns being joined. Surely enough compiler complained. I was pretty surprised why my code did not compile. I am sure many of you are SQL gurus and must have written joins and never cared that left column in the join clause must always come from the left table and right column in the join clause must come from right table. SQL server and many other database engines are pretty lenient in it. However Linq flavor requires your key selectors in the join clause must be in proper order. Basically left key of the key selector must come from left sequence or outer sequence. The right key of the key selector should come from right or inner sequence. Here is an example which C# compiler does not like because the order of the key selector is reversed.

  • PageLoad event firing twice

    On one of my projects I had the need to intercept the begin request and pageloaded event of page request manager. Begin request is an event raised by page request manager when a control inside of an UpdatePanel postback to the server. The event is raised just before the request is sent to the server. PageLoad event is a similar event but it gets raised the after the request has been received from the server and appropriate Update Panels have been updated. When I registered for pageloaded event and was manipulating the controls based on the data data received from the server, I was getting weird behaviors after resetting variables I had declared globally. To investigate the matter I put debug statements and sure enough confirmed that PageLoad event was firing twice. Here is an example that displays that behavior.

  • Table Valued Functions in Linq To SQL

    Linq to SQL supports both stored procedures and functions that can return result set. However there is a clear distinction in each approach. When you are using store procedures the data is returned as IEnumerable<T>. What this means is in the Linq query where you are calling the stored procedure, if you want to further apply more query operator meaning further filter the result  than that portion of the query will get executed as Linq to objects without you being aware of it. This could be great bottle neck if your stored procedure returns thousands of record and your applying filter that gets applied in memory instead of being sent as a part of query that gets executed on SQL server. In contrast if you are using table valued functions, data returned is in the form of IQueryable meaning you can further refine your query based on filters that you require. Those filters would become part of the SQL query that gets sent to the SQL server. To demonstrate this behavior I will start of with a table valued function and a stored procedure that returns customers based on city parameter.

  • anonymous types are readonly!!

    This was totally surprising when I learned in the usergroup meeting today that once you initialize an anonymous type you cannot change its properties after that. It is marked as read only. Following code does not compile.

  • Creating Extension methods with same name as instance methods

    I had a really good time at the user group meeting tonight. Learned some new stuff on linq. An interesting point one of my prior co-worker Matt mentioned was if you create an extension method with the same name as the instance level method on the class, the compiler does not raise any exceptions. For a second I didn't believe it and so I went home and tried. Sure enough he was true. I would think that it is illegal to declare an extension method with the same name as instance method because instance method should always take precedence over extension method. Also say if you had an extension method that does some stuff. Later you upgrade to a new framework and the framework also includes a method with the same name. Since C# compiler does not raise compilation error, you wouldn't know that in fact you are actually using the method implementation from the framework than your extension method which may not be the desired behavior. I am curious to know why other people think that C# compiler should not raise a compilation error in this scenario.

  • Using RegisterDataItem on ScriptManager

    Although there are different ways of sending data to client side from asp.net Ajax such as webservice, page methods, ScriptManager.RegisterStartupScript and many other ways. However my specific requirement was a bit different. I simply needed to send a value down to the client when a postback occurs through a button that is inside of an UpdatePanel, basically send additional data via ScriptManager to the client code when its sending the partial changes of the UpdatePanel down to the browser.You would want to use this technique if you are updating or want to update a control that is not part of an UpdatePanel. If the control that you are wanting to refresh is inside of an Update Panel, than simply calling UpdatePanel.Update would be sufficient enough. Here is the markup that shows how to send values down to the client code and updating a label on the client side with the data from the server.

  • Causing Full Postbacks from Inside of UpdatePanel

    Recently I had a need where I wanted to just make one control inside of my Update Panel fully post back to the server with out any asynchronous request. Well my need had to do with uploading a file which is an upload control followed by an upload button. If you have tried like me before you would realize that you cannot upload a file from inside of an Update Panel. It has to go through a regular postback to successfully upload the file to the server. If you have a similar need you can make use of triggers collection and add upload button as part of Postback trigger instead of an asynchronous postback trigger. Here is a simple markup that demonstrate the behavior.

  • Canceling Async PostBack

    Asp.net Ajax can perform at most one Async PostBack at a time. If the user initiates a second PostBack, it automatically aborts the previous request and initiates a new asynchronous PostBack. If this is not the behavior you desire, you have the ability to cancel new request until the existing request completes. In order to cancel new request you will have to register with beginRequest event of the pagerequest manager and check to see if there is an existing request that has not completed. If it is not completed than you can cancel the new request. The reason asp.net Ajax has limitations for only 1 Async PostBack is because of viewstate. If it were to allow more than 1 request than viewstate would get out of sync. If the current request takes too long to come back you can also have a cancel button on the UI and let the user cancel the existing page request. Here is the markup that I have written that displays the behavior.

  • Tracing Asp.net Ajax Client Side Request

    When you add script manager control on the page, it not only goes though page life cycle on the server but the request goes through series of events on the client side. There are two client side objects available in asp.net Ajax; Sys.Application and Sys.WebForms.PageRequestManager object. Sys.Application events are raised because of scriptmanager and PageRequestManager events gets raised only when there are updatePanels present on the page. In order to illustrate all these events I will use tracing feature available in asp.net Ajax. By using Sys.Debug.trace, I will write trace messages to a textarea with id equal to TraceConsole. If you have Firebug extension installed on firebox, the traces get automatically written to the trace console of Firebug. Here is how my markup looks like.

  • Sending script After Async PostBackPostBack

    I am sure many of you have been in a situation where you have a form view or details view control inside of an UpdatePanel and after inserting a successful record into the database you went to send a small JavaScript to the end user saying that your record got successfully inserted into the database. I made use of ItemInserted event of FormsView control and used the Page.ClientScript.RegisterStartupScript to inject the JavaScript into the output stream. Unfortunately this ClientScript on the page object does not work when you are inside of an UpdatePanel. Here is the markup and codebehind of my page.

  • Setting Default Values on Your Custom Control

    Today when I was working with creation of server controls, I realized that I wanted my server controls to work out of the box using default values when you drag and drop the control onto the designer surface. That's when I started digging into what do I needed to do on my server controls to set default values. Sure enough I welcomed the new attribute ToolBoxData in which you can specify default values for the properties of your control when it gets dragged. Here is an example of Address server control in which I am setting default values for the properties address,city, state and zip on my address control.

  • How to avoid cc1 prefix when dragging server controls

    Continuing with my exploration in server controls, i discovered a small nuisance when i you drag your custom controls from the toolbox onto the designer. For some reason visual studio would automatically prefix the server control with cc1 tagprefix as shown in the example below.

  • RenderContents Using enumerations

    Continuing with my discovery of server controls, I have come across few more goodies. As I mentioned in my earlier blog posting that there are two different ways of writing content when you override RenderContents method inside of a server control. Here is an example of two different approaches.

  • Registering Server Controls in web.config

    If you have a custom server control that you are going to use in several different pages. It might be worth while to register the server control in web.config file instead of registering it in several different pages. Here is an example of registering my custom controls library in web.config file.

  • Deploying assemblies to GAC

    This topic may not sound too interesting too people because it is an old story. Basically in order to store anything in gac you have to strongly name an assembly. I don't  happen to put assemblies in GAC too often so I simply forget the process of strongly naming an assembly. This time around I decided to write a blog post so that I would always have something to look back into.

  • Initializing Controls in CreateChildControls

    Once again in my adventure of writing custom controls I have discovered that if you are overwriting custom CreateChildControls to add your own controls to the control collection, you should initialize the controls before adding them to the control collection.  Here is an example where I am setting properties on the link button after I add them to the controls collection. 

  • Using RenderBeginTag

    At my current work, I had my share of custom controls that I have to write. Basically I started to write my html by overriding the render contents. I had been using the old style RenderBeginTag and than add my styling by calling write attribute. It is nice but the problem that I have with is at the end I have to know which tag to close which is sometimes a pain. Therefore when I found this new method called RenderBeginTag, I thought it was nice because when I have to close the tag I simply have to say RenderEndTag and it automatically figures out the tag I have to close. Here is a simple code showing two different ways of doing it.

  • Overriding ConnectionString in DataContext

    Today at work, one of my co-workers mentioned an issue that he was loosing ConnectionString every time he would modify the linq to SQL model in the dbml file. What he was essentially doing was getting rid of the default constructor and adding a partial class where in the default constructor based on business rules, he would fetch the right ConnectionString either from web.config, app.config or some other xml file. Obviously the problem here was, you cant have two default constructors. Because every time you would modify the dmbl file any changes you have made to the designer.cs would get lost. But a simpler solution to this would simply be creating your own partial DataContext class and adding the OnCreated partial method which gets called in the default constructor. Here is a simply implementation where I am reading the ConnectionString from web.config ConnectionString section.

  • Working With Expression Trees

    Now I am not going to be talking about expression trees in depth. I will be covering expression trees at basic level. The reason I started playing around with expression tree was not to write a provider but basically to be able express my intent at runtime. Linq is so much at compile time that sometimes it is not feasible for dynamic queries. This is where you can use expression trees that allows you define your intent based on runtime decisions.

  • ConvertAll delegate

    Today I had the need to convert a list of objects in a collection to a list of different objects in a collection. Although its a pretty simple use case which would not require too much manual code to do it. But surely enough I got introduced to a build in method Convert that is available on List<T>. Convert pretty much tells you by name what its purpose is. It converts one collection to another collection by taking a delegate which specifies how to to transform one object to another. Here is an example that shows how to use ConvertAll.

  • Implicit Arrays

    One of new features in C# 3.0 that I am really fond of, is not having to declare what type of array it is. It starts by checking all the values in the array and seeing if they can be implicitly converted to one type. If it can, than it is considered the array type.

  • Var cannot be used as instance level variable

    Today I was playing around with Var and I decided to try to implicitly declared some of my instance level variables. Unfortunately compiler raises an error saying Var can only be used in the scope of local variable. Here is an example.

  • Unique Behavior when querying using primary key column in linq to SQL

    I was working on a query earlier in the day when I came across this behavior when searching for a record using primary key in linq to SQL. Basically when you query for an object the first time using linq to SQL, datacontext caches the object in its tracking service. Therefore next time around when you query for the object again, it retrieves the modified object from the cache. It is worth noting that if you are querying based anything that is not a primary key column than linq to SQL would make a database call the second time around as well. After completing the database call, it will than check with the data tracking service to see if that object is available in its cache. If it is available, it will return the object from its tracking service. However when you are querying based on primary key column, it does not bother making the database call, it simple ask the object from the tracking service first and if it is found it simply returns it. If the tracking service does not have the object than linq to SQL goes and makes a database.

  • Useful tip to infer types in Visual Studio.

    There are times when your linq query would return complex data. If you are not exactly sure what the return type is, than simply assign the result to var and hover over the var to see its exact type. Here are two examples that illustrates the beauty.

  • Partial Methods

    Partial methods is a new feature available in C# 3.0. Partial methods allow hooks into automatically generated code. Partial method basically consist of definition and implementation. Usually you define and declare partial method in one partial class and implement in another. Partial methods are heavily used by code generated from linq to SQL.

  • Static Classes in C# 2.0

    In C# 1.0 if you wanted to ensure that no outside user can create an instance of class and that class user should use static method or properties to use the class,  you would normally mark the class as sealed and make the constructor private. When you make the constructor private, no outside user can create an instance of the class. Marking the class as sealed prevents any outside user to extend the behavior of the class. However the draw back to this approach is having two change two things and secondly you can get away with declaring instance level properties or method without compiler raising an error. Obviously those methods and properties are pretty much useless since no one can create an instance of the class. Here is how you would create the class in C# 1.0.

  • Loading Child Entities With Deferred Loading Turned Off

    If you have a situation where you do not want to risk your code making too many database calls without you knowing about it. You have the ability to turn off deferred loading by setting DefferedLoadingEnabled to false. However when you set it to false, you loose the ability to fetch that object or collection of objects anymore. What you can do is take control of loading those child entities in your query explicitly. Let's look at an example where deferred loading is turned off and the results you get when you access the child collection.

  • Group by multiple columns in Linq To SQL

    Today I was writing a Linq query in which I wanted to applying grouping to query based on more than 1 column and also apply filter on the group more like having clause. After some playing I figured it out. Here is a simple demonstration of grouping by more than 1 column using customer table from NorthWind database.

  • Action delegate in C# 2.0

    I have used in the past predicate delegate, which is used when you want to test for a certain condition. However Action delegate is used when you want to perform certain action on specified value. The specified value could be complex type or value type. It could be printing to console window or modifying the current object or value. Here is simple example in which I am making use of Action<T> delegate.

  • Using Linq To SQL with ObjectDataSource Control

    In my previous blog posting I showed how to use linqdatasource with gridview,detailsview and formview to insert, update and delete records using NorthWind context. Linqdatasource is a nice control to have, however I feel that it forces me to put too much business logic in my aspx file. Not only that, it also forces me to expose my datacontext to my presentation layer. In this small example I making use of ObjectDataSource control to insert,update delete and select records using my business objects.

  • My vacation pictures

    I had a really good time during my vacation at disney. I had been meaning to post my vacation pictures but have been really occupied at work and learning new stuff. Finally i was able to find sometime to get all the pictures uploaded to flick.

  • Using Linq To SQL With WCF Service

    The other day I met someone in the usergroup who asked me if I know how to use Linq to SQL classes in wcf and if Linq to SQL classes were serializable over the wire. I haven't done any wcf except attended quite a few talks on WCF. I decided to research of what I need to do to consume my Linq to SQL classes using wcf service with asp.net as a presentation layer. Here is a small walk through that illustrates an example of that. I am going to be demonstrating the example using Customer class from NorthWind database.

  • Using LinqDataSource for Inserts,Updates and Deletes

    In this small walk through I will demonstrate how to use linq datasource to do insert,update,delete and select using form view,gridview and details view control. I will use Formview control to do inserts and use gridview to do updates and deletes. When you select a row in the grid, the detail record will be displayed in a details view control. The screen shot of the page looks like this.

  • ObjectTrackingEnabled Does not Work!

    Today I was messing around with the datacontext that I created for linq to SQL NorthWind database. One of the ways to improve performance for the datacontext for web scenarios is turn off object tracking on the context. If you are using the context for read only purpose rather than insert update or delete, than you do  not need to bear the heavy cost of object tracking service. But what I have found out recently is, if you turn off object tracking on your datacontext, you loose the ability to traverse relationship. For example, if you traversing one one to one relation like Customer.Address.City than you would get a null reference exception. If you navigate a many to many relationship like Customer.Orders.Count(), you will get 0 despite the fact that a particular customer would have orders.

  • Invoking Generic Methods Using Reflection

    This is by no means any detailed post on how to use reflection. The other day I had the need to use reflection to call a generic method. So after playing around with reflection for few minutes I figured it out.  Here is how the code looks like.

  • Static fields in Generics

    If you have used static fields before you would be aware that no matter how many instances of a class you create, you will always end up sharing the static field among all instances and there will be only 1 value. Changing the static value would effect and reflect the new value for all instances of the class as shown below.

  • How To Hide IntelliSense

    Another neat trick that I learned recently is using the Cntrl key. There are times when you are coding and need to see something that gets hidden behind the intellisense window. Instead of pressing Esc to get rid of the window, I find it easier to hold down the Cntrl key which fades the intellisense as long as you have the key pressed. Nice features that saves some time.

  • Comparison Using Generics

    As I was playing with generics, I found something really interesting in terms of comparing two reference types using generic method. For example, when you compare two reference types using == or !=, you are basically comparing the references of those two objects. However when you compare two strings, you are actually comparing two values to see if they are equal instead of comparing references. This is because string class overloads those operators to define a different implementation of == and != operator. When you apply comparisons in generic methods, you would be using the default implementation of == and != that is defined by the object type. This is because the compiler resolves the method using unbound generic type and does not try to accommodate all the possible method calls based on different generic type which may have overloaded the == and != operator. Because of this limitation you may not get the correct comparison achieved in generic method as shown below.

  • Type Inference in Generics

    If you are using generic method, you can call the method without explicitly specifying the type arguments. Their are certain cases where the compiler cannot infer the type based on the values passed in the parameters, in those cases you can explicitly specify the type argument. Depending on the scenario,it might be concise syntax but may not be readable to another developer. Here is an example of using generic method with and without explicitly specifying the type.