#276 – Passing a struct by Reference

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:


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: