Wednesday, March 24, 2010

Passing Structs and Classes to Methods

Structs, being value types, are created on the stack. When passed to methods, they are passed by value. Since classes are reference types, they are created on the heap. When passed to methods, they are passed by reference.
The following example demonstrates this concept. In the example, we declare a class called MyClass and a struct called MyStruct. Then we instantiate the class and the struct and initialize the field in each with value 555. We pass both objects to the methods MyMethod1 and MyMethod2 to change their fields to 100. The output, however, indicates that the field of the class has changed but not that of the struct.
//Example7-3.cs
//Passing struct & class objects to methods
using System;
class MyClass
{
    public int classField;
}
struct MyStruct
{
    public int structField;
}
class MainClass
{
    public static void MyMethod1(MyStruct s)
    {
        s.structField = 100;   
    }
    public static void MyMethod2(MyClass c)
    {
        c.classField = 100;
    }
    static void Main()
    {
        //Create class and struct objects:
        MyStruct sObj = new MyStruct();
        MyClass cObje = new MyClass();
        //Initialize the values of struct and class objects:
        sObj.structField = 555;
        cObj.classField = 555;

        //Display results:
        Console.WriteLine(“Results before calling methods:”);
        Console.WriteLine(“Struct member = {0}”, sObj.structField);
        Console.WriteLine(“Class member = {0}\n”,cObj.classField);

        //Change the values through methods:
        MyMethod1(sObj);
        MyMethod2(cObj);
        //Display results:
        Console.WriteLine(“Results after calling methods:”);
        Console.WriteLine(“Struct member = {0}”, sObj.structField);
        Console.WriteLine(“Class member = {0}” , cObj.classField);
    }
}

No comments:

Post a Comment