This is a blog where I try to describe the lessons that I learn on my journey on .NET. My aim here is to spread the knowledge that I gain which will help all of us to be a better developer. In this blog I will explain the books, other articles as well as my own experiences which I go through everyday and hope everybody benefits from them.

Thursday, March 10, 2016

Struct vs Class in C#

In today's blog post, we will be discussing the differences between struct and class in C#.

Struct Vs Class

Struct and Class are both constructs of the common type system in the .NET framework. Both are used to encapsulate data and behavior as a logical unit. While declaring, both look similar, except they keyword "struct" and "class" :)

The major difference between struct and class is that class is a reference type and struct is a value type. I have talked about reference vs value type before here.

A reference type is allocated on heap. It's garbage collected at frequent intervals (will cover garbage collection in another post). When a new variable is created pointing to such an existing object, no new object is created. The new reference points to the same object. So any changes made to the object using one reference is visible on the other because the underlying object is the same.

A value type is allocated on the stack. Value type is deallocated when the stack unwinds or when their containing type gets deallocated. The variable which defines the struct actually holds the data itself. When a new variable is assigned to an existing struct, a new copy of data is created and held by the new variable. So changes made to one copy are not reflected by the other.

In general, structs are limited as compared to classes. Here are some of the other differences:

In a struct, the fields cannot be initialized (except const or static).

There can be no default constructor (parameter-less constructor) or a destructor in a struct. However, structs can have constructor(s) with parameter(s).

Struct can be instantiated without the new operator.

A struct can not inherit from another struct or class. However, a struct can implement interfaces.

Conclusion

Although, most of the times, we lean towards classes as compared to structs. Classes give us more power and ease of use. Mostly people use structs for small and light-weight data. However, it's still important to understand the difference between the two and use the right thing accordingly.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)Follow @abhijain369

It depends on how you use it? If you have a lot of boxing and unboxing going on with the usage of struct, it might impact the performance negatively. However, if you just want to use it for something small and which doesn't require boxing and unboxing, structs might be preferable there.