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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube