C# Programming Guide
How to: Know the Difference Between Passing a Struct and Passing a Class Reference to a Method (C# Programming Guide)

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

The output of the following example shows that only the value of the class field is changed when the class instance is passed to the ClassTaker method. The struct field, however, does not change by passing its instance to the StructTaker method. This is because a copy of the struct is passed to the StructTaker method, while a reference to the class is passed to the ClassTaker method.

Example

C#
class TheClass
{
    public string willIChange;
}

struct TheStruct
{
    public string willIChange;
}

class TestClassAndStruct
{
    static void ClassTaker(TheClass c)
    {
        c.willIChange = "Changed";
    }

    static void StructTaker(TheStruct s)
    {
        s.willIChange = "Changed";
    }

    static void Main()
    {
        TheClass testClass = new TheClass();
        TheStruct testStruct = new TheStruct();

        testClass.willIChange = "Not Changed";
        testStruct.willIChange = "Not Changed";

        ClassTaker(testClass);
        StructTaker(testStruct);

        System.Console.WriteLine("Class field = {0}", testClass.willIChange);
        System.Console.WriteLine("Struct field = {0}", testStruct.willIChange);
    }
}

Output

Class field = Changed
Struct field = Not Changed

See Also

Tags :


Community Content

Laszlo Siroki
How to change a field of a struct

If you do want to change the value of a field of a struct, which is passed as parameter, you should pass the parameter as reference.

The method should look like this:

    static void StructTakerReference(ref TheStruct s)
{
s.willIChange = "Changed";
}


It can be called as:

StructTakerReference(ref testStruct);

Page view tracker