changing mutable list in extension method

8 views
Skip to first unread message

Bruce Anderson

unread,
Feb 10, 2013, 3:59:52 PM2/10/13
to nemer...@googlegroups.com
How can I get this to work:

    mutable t : list[string] =   [];
    t.push("hello");

where push is defined as an extension method:

    public class ListExt{
        public static push['t]  (mutable this lst : list['t], el : 't) : void {
            lst ::= el;
        }
    }

?  What I'm seeing is that lst changes within the extension method, but the original t does not change.

Thanks in advance,

Bruce

NN

unread,
Feb 11, 2013, 1:55:18 AM2/11/13
to nemer...@googlegroups.com
list is immutable data structure, like string.
So you cannot change the list by passing it to method, only if you pass it as ref.
If you want a list where you can add values using extension method use System.Collections.Generic.List.

This is sample in C# with string demonstrating the same problem:

static class P
{
   public static void push(this string s, string p) { s += p; }
}  

class Q
{
   static void Main()
   {
     string x = "";
     x.push("a");
     System.Console.WriteLine(x);
Reply all
Reply to author
Forward
0 new messages