c# - Goto in the ElementAt extension method -


i looking code generated .net reflector of linq extension method elementat, , see code:

public static tsource elementat<tsource>(this ienumerable<tsource> source, int index) {     tsource current;     using (ienumerator<tsource> enumerator = source.getenumerator())     {     label_0036:         if (!enumerator.movenext())         {             throw error.argumentoutofrange("index");         }         if (index == 0)         {             current = enumerator.current;         }         else         {             index--;             goto label_0036;         }     }     return current; } 

i think can write same thing without goto statement. like:

public static tsource elementatbis<tsource>(this ienumerable<tsource> source, int index) {     using (ienumerator<tsource> enumerator = source.getenumerator())     {         while (enumerator.movenext())         {             if (index == 0)             {                 return enumerator.current;             }             else             {                 index--;             }         }         throw new argumentoutofrangeexception("index");     } } 

so wondering why elementat written way. there kind of conventions here? maybe rule have 1 return statement last line of function? or maybe i'm missing performance? or .net reflector have problem?

as side note, method elementatordefault doesn't use goto statement:

public static tsource elementatordefault<tsource>(this ienumerable<tsource> source, int index) {     using (ienumerator<tsource> enumerator = source.getenumerator())     {         while (enumerator.movenext())         {             if (index == 0)             {                 return enumerator.current;             }             index--;         }     }     return default(tsource); } 

it's matter of decompiler. next code produced decompiling mscorlib assembly's method elementat dotpeek:

public static tsource elementat<tsource>(this ienumerable<tsource> source, int index)  //...omitted code validation  using (ienumerator<tsource> enumerator = source.getenumerator()) {    while (enumerator.movenext())    {       if (index == 0)          return enumerator.current;       --index;    }    throw error.argumentoutofrange("index"); } 

il instructions doesn't have while construction. next code demonstrates this:

while(true) {     console.writeline ("hi there"); } 

is compiled into:

il_0000:  ldstr       "hi there" il_0005:  call        system.console.writeline il_000a:  br.s        il_0000    //unconditionaly transfers control il_0000. it's goto il_0000; in il 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -