- articlesbyJosephMayo
- C# Reference and Value Method Parameter Type Behavior with Classes and Structs
- Joe's Tips
- Joe's Tricks
C# Reference and Value Method Parameter Type Behavior with Classes and Structs
There are four ways to declare method paramenters. Two of the ways are by reference or by value. Passing by reference provides a pointer to a single field. Changes to the field within the method modify the original field. Passing by value copies a field, leaving the original field untouched.
This is all straightforward, until you consider the different C# types: classes (reference types) and structs (value types). This program demonstrates the results of class and struct parameters passed by reference and value:
using System;
struct MyValType { public int myValInt; }
class MyRefType { public int myRefInt; }
class RefValParams { void ModValOnStruct(MyValType mvtByVal) { mvtByVal.myValInt = 1; }
void ModRefOnStruct(ref MyValType mvtByVal) { mvtByVal.myValInt = 2; }
void ModValOnClass(MyRefType mrtByRef) { mrtByRef.myRefInt = 1; }
void ModRefOnClass(ref MyRefType mrtByRef) { mrtByRef.myRefInt = 2; }
static void Main(string[] args) { RefValParams myRVParams = new RefValParams(); MyValType myValue = new MyValType(); MyRefType myReference = new MyRefType();
Console.WriteLine( "Initial struct value: {0}", myValue.myValInt);
myRVParams.ModValOnStruct(myValue);
Console.WriteLine( "Struct after ModValOnStruct: {0}", myValue.myValInt);
myRVParams.ModRefOnStruct(ref myValue);
Console.WriteLine( "Struct after ModRefOnStruct: {0}", myValue.myValInt);
Console.WriteLine("\n");
Console.WriteLine( "Initial class value: {0}", myReference.myRefInt);
myRVParams.ModValOnClass(myReference);
Console.WriteLine( "Class after ModValOnClass: {0}", myReference.myRefInt);
myRVParams.ModRefOnClass(ref myReference);
Console.WriteLine( "Class after ModRefOnClass: {0}", myReference.myRefInt); } }
Here's the output:
Initial struct value: 0 Struct after ModValOnStruct: 0 Struct after ModRefOnStruct: 2
Initial class value: 0 Class after ModValOnClass: 1 Class after ModRefOnClass: 2
This program creates instances of a struct and a class and sends each to methods accepting reference and value type parameters. As shown, structs adhere to the parameter specification, but classes are always passed by reference, regardless of the parameter type.