Structs

Classes are great for implementing objects. However, there may be times when you feel that an object should behave like one of the built-in types, something fast to allocate without much of an overload, and overhead of references. The answer is to use structs (short for Structures). Unlike the structs of C/C++, the structures in C# can have methods defined within them. They can have a constructor too.

Consider the following example,

Example 16:

Structs Example 16

As you can see we have a constructor, a method, and a data member in our structure TestStruct. Recall that in C/C++ we could only have data members in structures. No methods or constructors were allowed.

If structs can have methods and constructors then how are they different from classes is a good question to ask. Structs do have their own restrictions. They cannot implement inheritance. Secondly and most importantly structs are of value types while classes are of reference types. Structs are stored in a stack while classes on a heap!

In C# the simple types are actually structs that can be found in the System namespace. For example, the long type is an alias for System.Int64 struct. This means that when you are working with simple types you are actually working with the structs in the base class.

Leave a comment