Export (0) Print
Expand All
3 out of 5 rated this helpful - Rate this topic

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.

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";


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

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
/* Output:
    Class field = Changed
    Struct field = Not Changed

Community Additions

© 2014 Microsoft. All rights reserved.