Struct Instances vs. Class Instances

Classes are reference types.

A variable of a class object holds a reference to the object.

Two class variables may refer to the same object.

Instances of classes are created by using the new operator.

In the following example, Person is the type and person1 and person2 are instances, or objects, of that type.


using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

class Program
{
    static void Main()
    {
        Person person1 = new Person("Jack", 6);
        Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

        // Declare  new person, assign person1 to it.
        Person person2 = person1;

        //Change the name of person2, and person1 also changes.
        person2.Name = "Tom";
        person2.Age = 16;

        Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);
        Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

    }
}

The output:


person1 Name = Jack Age = 6
person2 Name = Tom Age = 16
person1 Name = Tom Age = 16

Structs are value types.

A variable of a struct object holds a copy of the entire object.

Instances of structs can also be created by using the new operator, but this is not required.


using System;

public struct Person
{
    public string Name;
    public int Age;
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

public class Application
{
    static void Main()
    {
        // Create struct instance and initialize by using "new".
        Person p1 = new Person("Jack", 9);
        Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);

        // Create new struct object. 
        Person p2 = p1;

        // Assign values to p2 members.
        p2.Name = "Tom";
        p2.Age = 7;
        Console.WriteLine("p2 Name = {0} Age = {1}", p2.Name, p2.Age);

        // p1 values remain unchanged because p2 is  copy.
        Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);

    }
}

The output:


p1 Name = Jack Age = 9
p2 Name = Tom Age = 7
p1 Name = Jack Age = 9
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.