#275 – Passing a struct to a Method

You can pass an instance of a struct type to a method.  By default, the struct is passed by value, which means that a copy of the struct’s data is passed into the method.  This means that the method cannot change the contents of the original struct.

For example, assume you’ve defined the following struct:

    public struct MovieInfo
        public string Title;
        public int Year;
        public string Director;

A method that accepts an instance of this struct as a parameter might look like:

        public static void DisplayMovieInfo(MovieInfo minfo)
            Console.WriteLine("{0} ({1}), dir by {2}", minfo.Title, minfo.Year, minfo.Director);

And calling the method would look like this:

MovieInfo minf = new MovieInfo();
minf.Title = "Citizen Kane";
minf.Year = 1941;
minf.Director = "Orson Welles";

Movie.DisplayMovieInfo(minf);   // Passed by value -- copy of minf passed to method

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: