Practical .NET

Use Structs Instead of Classes to Pass Data Uniquely

The difference between Structs and Classes isn't about data vs. code: it's about what happens when you move the data around. And sometimes you want a Struct, not a Class.

Many times, when you create a class, you would have been far better off to create a Struct. The obvious example of a Struct in C# is:

public struct Person
{
     public string Name

     public int Age
}

And many developers are under the impression that's all a Struct can do: hold variables. But, in fact, Structs can hold methods and properties, as this Visual Basic example does:

Public Struct Person

     Public Name As String

     Private _Age As Integer

     Public ReadOnly Property Age As Integer

	Get

		Return _age

	End Get

     End Property

     Public Function HaveBirthday()

          Me.Age += 1

          Return Me.Age

     End Function

End Struct

The savings come in when you declare a variable using a Struct: you don't have to instantiate your variable, saving the code that uses the new keyword. You just declare the variable with the datatype. In C#:

Person pers;

pers.Name = "Peter Vogel";

In Visual Basic:

Dim pers As Person;

pers.Name = "Peter Vogel"

And that's great, but not much of a savings. The real payoff is that a Struct is a value type. That means that if you assign a struct to another variable, the other variable gets its own copy of the data. Look at this code:

Person pers2;

pers2 = pers;

pers2.Name = "Peter Vogel";

If Person was a Class, then both the pers and pers2 variables would point at the same object and updating pers2.Name would also update pers.Name. However, because they're Structs, pers2 gets its own copy of the data in pers, and updating pers2 only updates pers2. If, in your code's mainline, you pass a Struct to a method and the code in the method updates the Struct, the version of the Struct in your mainline is unaffected.

I recently took advantage of this in a multi-threading application. In my "master" method, I loaded up a Struct with control information that all the threads I was going to spin off would need. I then passed that Struct to each thread where they updated and added to the control information. Periodically, the "master" class would retrieve the Struct from each thread to see how it was doing, and update some of the information in each Struct.

If I'd used a single Class, that Class would have been shared between all threads and the master "method"; great for communication between threads, but lousy for thread isolation, which is what I needed. I could have instantiated a Class for every thread, but that would have meant loading each Class with the control information that was identical for every class. By using a Struct, I only had to do it once.

So, the next time you go to create a Class ask yourself: Do I want Class behavior or Struct behavior? And, if you think about it, you may decide that you want Struct behavior.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube