1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By , About.com Guide

2 of 10

Structs are Lightweight Objects

In C++ a struct is just a class with default public access. In C# it is like a class but much more limited and is a value type so is stored on the stack. It is closer to the original use of a struct in C where it was just a place to hold data. A struct cannot inherit from a struct not can it be inherited from.

To confuse matters slightly, a struct can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. A default constructor is provided by the compiler so you can initialize it with constructor type syntax. But you cannot write a default constructor for a struct yourself. Any constructors you write for a struct must have parameters.

Download Example 1

This example demonstrates a simple struct type that has two public ints a and b. In a C# struct, everything is private unless explicitly declared public, the opposite of C++.

  struct struct_test
  {
    public int a;
    public int b;

    public struct_test(int newa,int newb) { // constructor
      a = newa;
      b = newb;
    }

    public override string ToString() {
      return a.ToString() + " " + b.ToString() ;
    }
  }
The ToString() function overrides the function object.ToString(). All C# variables can do this. This provides an easy way to print out the value of a variable. By default though, for objects and structs, ToString() returns the name of the variable. You can override it, as I did to provide something more useful.

On the next page : More About Structs

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Structs are Lightweight Objects

©2009 About.com, a part of The New York Times Company.

All rights reserved.