Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Structs in C#, Structs vs. Classes, Heap or Stack? Structs Constructors

0.00/5 (No votes)
25 Sep 2007 2  
This article describes Structs in C#, Structs vs. Classes, Heap or Stack? Structs Constructors

Introduction

This simple article describes structure syntax and usage of structs. This article also covers the important differences between classes and structs, default constructors and heap or stack?

Background

A C# structure is a value type and the instances or objects of a structure are created in stack. The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types.

A structure in C# is simply a composite data type consisting of a number of elements of other types.

The .NET Framework defines built-in value types, such as System.Int32 and System.Boolean, which correspond and are identical to primitive data types used by programming languages.

All built-in value types are structures in .NET. In .NET, all Value types and Reference types are derived from System.Object. The System namespace is the root namespace for fundamental types in the .NET Framework. This namespace includes classes that represent the base data types used by all applications: Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, String, and so on. Many of these types correspond to the primitive data types that your programming language uses.

All of the simple types are aliases of the .NET Framework System types. For example, int is an alias of System.Int32. The C# type keywords and their aliases are interchangeable. For example, you can declare an integer variable by using either of the following declarations:

int i=32; 

or:

System.int i=1;

As I have already described. The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types.

Now let's have look at each step by step.

Using the Code

// MyFirst_Struct.cs
using System;
struct SimpleStruct
{
    //how the fields are declared in the structure.
    private int _value;
    // how the properties are declared in the structure.
    public int MyProperty 
    {
        get 
        {
            return _value;
        }
        set 
        {
            if (value < 100)
            _value = value;
        }
    }
    // how the methods are declared in the structure
    public void Display_value()
    {
        Console.WriteLine("The stored value is: {0}", _value);
    }
    // Default Constructors
    SimpleStruct ()
    { 
        //A struct type is however permitted to declare parameterized //constructors. 
    }
}

class MyTestClass
{
    public static void "on" />Main()
    {
        SimpleStruct ss = new SimpleStruct();
 
 
        ss. MyProperty = 310;
        ss.Display_value();
    }
}

Output

The stored value is: 310

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

// MySecond_Struct.cs
using System;
class TheClass
{ 
 public int x; 
} 

struct SecondStruct
{ 
 public int x; 
}
 
class TestClass
{
    public static void structtaker(SecondStruct _Struct) 
    { 
        _Struct.x = 5;
    }
 
    public static void classtaker(TheClass _Class)  
    { 
        _Class.x = 5; 
    } 
 
    public static void "on" />Main()
    {
        SecondStruct ss = new SecondStruct();
        TheClass tc = new TheClass();
        ss.x = 1;
        tc.x = 1;
        structtaker(ss);
        classtaker(tc);
        Console.WriteLine("ss.x = {0}", ss.x);
        Console.WriteLine("tc.x = {0}", tc.x);
     }
} 

Output

ss.x = 1
tc.x = 5

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

Default Constructors

In C#, every value type implicitly has a public parameter less default constructor. Like any other constructor, the default constructor of a value type is invoked using the new operator. So it is not possible for a struct type to contain an explicit declaration of a parameter less constructor.

You are also introduced to the following topics:

  • Structs vs. Classes
  • Heap or Stack?
  • Constructors

Structs vs. Classes

Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.

Heap or Stack?

When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference.

Conclusion

Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing with them directly. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.

History

  • 25th September, 2007: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here