Struct Instances vs. Class Instances
In this chapter you will learn:
Struct vs Class
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;/*from ja va2s . com*/
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:
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;//from j a va 2s. c o m
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:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class