#276 – Passing a struct by Reference
March 20, 2011 Leave a comment
You can pass a struct by reference using the ref or out parameter modifiers. Use ref when you want a method to read and write to the struct. Use out for a struct that is meant to be an output parameter.
Assuming that you’ve defined the following struct:
public struct MovieInfo { public string Title; public int Year; public string Director; }
You might pass an instance of MovieInfo by reference like this:
public static void DisplayThenUpper(ref MovieInfo minfo) { Console.WriteLine("{0} ({1}), {2}", minfo.Title, minfo.Year, minfo.Director); minfo.Title = minfo.Title.ToUpper(); minfo.Director = minfo.Director.ToUpper(); }
After we call the method, the contents of the struct have been modified.
MovieInfo minf = new MovieInfo(); minf.Title = "Citizen Kane"; minf.Year = 1941; minf.Director = "Orson Welles"; Movie.DisplayThenUpper(ref minf); Console.WriteLine("{0}, {1}", minf.Title, minf.Director);
Output after the program has finished: