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

  • Microsoft Revamps Fledgling AutoGen Framework for Agentic AI

    Only at v0.4, Microsoft's AutoGen framework for agentic AI -- the hottest new trend in AI development -- has already undergone a complete revamp, going to an asynchronous, event-driven architecture.

  • IDE Irony: Coding Errors Cause 'Critical' Vulnerability in Visual Studio

    In a larger-than-normal Patch Tuesday, Microsoft warned of a "critical" vulnerability in Visual Studio that should be fixed immediately if automatic patching isn't enabled, ironically caused by coding errors.

  • Building Blazor Applications

    A trio of Blazor experts will conduct a full-day workshop for devs to learn everything about the tech a a March developer conference in Las Vegas keynoted by Microsoft execs and featuring many Microsoft devs.

  • Gradient Boosting Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the gradient boosting regression technique, where the goal is to predict a single numeric value. Compared to existing library implementations of gradient boosting regression, a from-scratch implementation allows much easier customization and integration with other .NET systems.

  • Microsoft Execs to Tackle AI and Cloud in Dev Conference Keynotes

    AI unsurprisingly is all over keynotes that Microsoft execs will helm to kick off the Visual Studio Live! developer conference in Las Vegas, March 10-14, which the company described as "a must-attend event."

Subscribe on YouTube