This is strange, I looked it up and by default C# should pass parameters by value but I've always had them get passed by pointer.

ie

public class foo
        {
            public foo()
            {
                derp = 123456;
            }

            public int derp;
        }

        public static void dontcare(foo z)
        {
            z.derp = 123;
        }

        static void Main(string[] args)
        {
            foo f = new foo();

            dontcare(f);

            Console.WriteLine(f.derp);

            Console.ReadLine();
        }

This prints out the value 123 instead of 123456.

Classes are passed by reference, value types and structs are passed by value. You have a class, so it's passed by reference. Just because it contains a value type doesn't make it one.

How do I force it to pass by value or create a new instance of the class and copy all the values without doing it manually with each variable. Thank you for the quick reply :]

There really isn't a good way to do this. The most common (that I've seen) is to create a copy constructor for the class and use that to pass a new object:

public class foo {
     public foo() {
         derp = 123456;
     }

     public foo(foo p) {    // Copy constructor
         this.derp = p.derp;
     }

     public int derp;
}

public static void dontcare(foo z) {
    z.derp = 123;
}

static void Main(string[] args) {
    foo f = new foo();

    foo p = new foo(f);
    dontcare(p);

    // or you can do
    // dontcare(new foo(f));

    Console.WriteLine(f.derp);

    Console.ReadLine();
}

I'd also like to add that technically objects are passed by value, but the value of an object is a reference to the actual object. So we tend to say that they are passed by reference :)

Edited 5 Years Ago by Momerath: n/a

That is pretty messy and doesnt avoid manually copying every value, are you sure there isnt another way.

There really isn't. You can do the copy part in different ways, but you still end up with a copy constructor.

Dude, just Use a Struct instead of a Class, Structs are pass by value instead of by reference.
http://msdn.microsoft.com/en-us/library/vstudio/ms173109.aspx

"A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy."

Structs are on the Stack, Classes are on the Heap.

This question has already been answered. Start a new discussion instead.