Value types - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Introduction

The content of a value type variable or constant is simply a value.

For example, the content of the built-in value type, int, is 32 bits of data.

You can define a custom value type with the struct keyword:

public struct Point { public int X; public int Y; }

or:

public struct Point { public int X, Y; }

The assignment of a value-type instance always copies the instance. For example:

Demo Code

using System;/*from  w w  w  . j  a  v  a  2 s .  c o m*/
public struct Point { public int X, Y; }
class Test
{
   static void Main(){
      Point p1 = new Point();
      p1.X = 7;
      Point p2 = p1;             // Assignment causes copy
      Console.WriteLine (p1.X);  // 7
      Console.WriteLine (p2.X);  // 7
      p1.X = 9;                  // Change p1.X
      Console.WriteLine (p1.X);  // 9
      Console.WriteLine (p2.X);  // 7
   }
}

Result


Related Tutorials