... like in Ruby

Is it possible to extend int (simple types) to be able do something like in this code, written in Ruby

3.times { print "X " }


Answer this question

... like in Ruby

  • simmy

    Sure, you can have

    static public IEnumerable<Int32> Yield(this Int32 subject)
    {
      for (int i = 1; i <= subject; i++)
        yield return i;
    }

    and then use 3.Yield() to get an enumerable containing [1, 2, 3].


  • Habib Heydarian MSFT

    Lovely!
  • Mark Ashton

    Making it possible to extend Int32 answer my question, thanks.

    I guess you can yield the values as well to be able to project an int to an enumerable


  • CG_JCAHO

    Yeah, I understand.  But what real world scenario would involve doing an operation on a literal value   I'm not picking on the feature, but rather asking a theoretic question. Is the ability to do it against a literal just a "you get it for free anyway" side effect of type extensions or is there a scenario where someone would really want to do this  

    Brian


  • Queue256

     Brian_Kramer wrote:

    the 3.Times example is pretty cool.  I'm curious: what kind of real-world scenario would call for operating on a literal like this  



    Hi Brian

    As a real world example you could take anything where you need a loop. The idea is to avoid an ordinary for next loop with this structure. the 3.Times example shows how a loop could look like in a purely object oriented program if we had the possibility of passing code blocks. A similar idea would be to do something like that for collections:

    aCollection.DoForEach(some code)

    Currently you can do this with delegates, but the delegate overhead makes it actually longer than an ordinary loop. This delegate overhead will disappear with the C# 3.0 compiler, which will resolve such passed code blocks in anonimous methods.




  • TenBaseT

    For the moment, you have to write it like that:

    delegate void Procedure();

    static class TestExtensions
    {
      static public void Times(this Int32 subject, Procedure procedure)
      {
        for (int i = 1; i <= subject; i++)
          procedure();
      }
    }

    Which allows you to write:
    3.Times(delegate {Console.WriteLine("X");});



  • Mariano Trinanes

    Hi

    What about the lambda function in C# Can they be used in order to make the code more like the ruby example By the way, will the lambda function be available in VB, too

  • Jobria

    the 3.Times example is pretty cool.  I'm curious: what kind of real-world scenario would call for operating on a literal like this  

    Brian


  • Matt Scott -- MSFT

    We'll definitely have support for them so that we can support LINQ in general. However, the exact form is yet to be determined...

    Paul
    VB Team

  • ... like in Ruby