Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# call by value/ref + extension methods

Tags:

c#

winforms

public static class RectangleExtension
{
    public static Rectangle Offseted(this Rectangle rect, int x, int y)
    {
        rect.X += x;
        rect.Y += y;
        return rect;
    }
}


....

public void foo()
{
    Rectangle rect;

    rect = new Rectangle(0, 0, 20, 20);
    Console.WriteLine("1: " + rect.X + "; " + rect.Y);

    rect.Offseted(50, 50);  
    Console.WriteLine("2: " + rect.X + "; " + rect.Y);

    rect = rect.Offseted(50, 50); 
    Console.WriteLine("3: " + rect.X + "; " + rect.Y);
}

Output:

1: 0; 0

2: 0; 0

3: 50; 50

What I expected:

1: 0; 0

2: 50; 50

why does rect.Offseted(50, 50) not modify the x and y of the rectangle in step 2?

What do I have to do with my RectangleExtension method to get my expected result?

like image 273
Felix Avatar asked Apr 22 '26 04:04

Felix


1 Answers

The answer is: structs are always passed by value in C#, and Rectangle in your case is a struct, not a class.

Try this:

public class A {
    public int x;
}
public struct B {
    public int x;
}
public static class Extension {
    public static A Add(this A value) {
        value.x += 1;
        return value;
    }
    public static B Add(this B value) {
        value.x += 1;
        return value;
    }
}
class Program {
    static void Main(string[] args) {
        A a = new A();
        B b = new B();
        Console.WriteLine("a=" + a.x);
        Console.WriteLine("b=" + b.x);
        a.Add();
        b.Add();
        Console.WriteLine("a=" + a.x); //a=1
        Console.WriteLine("b=" + b.x); //b=0
        Console.ReadLine();
    }
}
like image 157
kevin Avatar answered Apr 23 '26 19:04

kevin