Compartir a través de


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

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

Reference

Passing Parameters (C# Programming Guide)

Concepts

C# Programming Guide
Classes (C# Programming Guide)
Structs (C# Programming Guide)