MarzSocks
MarzSocks

Reputation: 4318

extension method not updating itself

Given the following object and its extension:

public class MyObj
{
    string var1 = "100";
    string var2 = "200";
}

public static void DoSomething(this MyObj myobj)
{
    myobj = new MyObj()
    myobj.var1 = "100000";
    myobj.var2 = "200000";
}

Note the extension method instantiates a new instance and assigns it to itself. When I do this however, my object is not actually updated as expected. It still contains the old variable values and is left untouched.

MyObj myobj = new MyObj();
myobj.DoSomething();

//myobj.var1 is still 100, but expected it to be 100000;
//myobj.var1 is still 200, but expected it to be 200000;

How do I get my object to update as expected - can this be done?

Upvotes: 2

Views: 1259

Answers (3)

Arthur Rey
Arthur Rey

Reputation: 3058

Another way to go if you want to keep the extension method:

public static MyObj DoSomething(this MyObj myobj)
{
    myobj = new MyObj()
    myobj.var1 = "100000";
    myobj.var2 = "200000";

    return myobj;
}

And you use it like so

MyObj myobj = new MyObj();
myobj = myobj.DoSomething();

Note that if your DoSomething method is just used to reset the object, you might as well use a constructor.

Upvotes: 1

Jacobr365
Jacobr365

Reputation: 846

You could just create a new object with a constructor like this.

MyObj(int x, int y)
{
    var1 = x;
    var2 = y;
}

and call like:

MyObj myobj = new MyObj(100,200);

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156948

You can't assign another instance to itself from an extension method. You are just changing the reference to the local variable myobj.

You can do this from a static method with ref:

public static void DoSomething(ref MyObj myobj)
{
    myobj = new MyObj()
    myobj.var1 = 100000;
    myobj.var2 = 200000;
}

Usage:

MyObj myobj = null;
DoSomething(ref myobj);
// myobj is set here

Upvotes: 5

Related Questions