Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic syntactic sugar or true improvement

I have a question regarding the following method calls:

var ctl1 = this.FindControlRecursively("SomeField") as HiddenField;
var ctl = this.FindControlRecursively<HiddenField>("SomeField");

Here's IL for these two calls:

IL_0010:  ldstr      "AsyncReset"
IL_0015:  call       class [System.Web]System.Web.UI.Control   [Amc.WebG081.MethodExtensions]Amc.WebG081.ControlExtensions::FindControlRecursively(class [System.Web]System.Web.UI.Control,string)

IL_001a:  isinst     [System.Web]System.Web.UI.WebControls.HiddenField
IL_001f:  stloc.0
IL_0020:  ldarg.0
IL_0021:  ldstr      "AsyncReset"
IL_0026:  call       !!0 [Amc.WebG081.MethodExtensions]Amc.WebG081.ControlExtensions::FindControlRecursively<class [System.Web]System.Web.UI.WebControls.HiddenField>(class [System.Web]System.Web.UI.Control,string)

I've always thought in this situation, the generic version of this method was more "syntactic sugar" vs. true improvement. Is the IL telling a different story?

like image 247
Pat Lindley Avatar asked Dec 29 '11 20:12

Pat Lindley


2 Answers

Generics are built into C#, so it is a "true improvement". Hence why run-time co-variance and contra-variance is possible, as well as reflection on generic types and run-time reflection-based creation of generic types (such as List<T> where T is determined at run-time).

This differs from C++, where templates are, in a lot of ways, syntactic sugar. The compiler actually generates code for each generic type you use - so Add<T> would create Add<int>, Add<long>, Add<short>, Add<MyClass>, and so on if you were using those functions, and likewise for classes. The benefit of this is primarily operators and a few other smaller things - if each of those types has a + operator, and Add<T>(T a, T b) returns a + b, all types will work just fine. C#'s compiler would complain because it can't/doesn't resolve the operator declaration for any-and-all types at compile time. Moreover, C# (not 100% sure, but maybe 90%) creates 1 generic type implementation for reference types (if you're using that implementation) and then 1 for each value type (so int, long, Decimal, MyStruct, etc all get their own implementations, as needed).

like image 166
GGulati Avatar answered Sep 26 '22 00:09

GGulati


In java, generics are syntactic sugar but in c#, they are built in. look at this: www.25hoursaday.com/CsharpVsJava.html

like image 41
prongs Avatar answered Sep 25 '22 00:09

prongs