C# Objects: A Deep Dive

C# Programming tutorials

Object-oriented Programming (OOP) is a method of building code that models the real-world using objects. Objects are the building components of an application in object-oriented programming. Classes have attributes and methods that specify the behavior of your objects in specific contexts or scenarios. Each object is made up of a collection of attributes and methods.

In C#, a class acts as a blueprint for creating instances of itself. Objects represent individual copies of this blueprint that can be created, destroyed, or altered as needed. This programming tutorial discusses objects, their types, and how developers can work with them in C#.

You can learn more about classes in C# by reading our tutorial: Introduction to C# Classes.

Struct Instances vs. Class Instances in C#

Structs are value types, which means that they are stored on the stack rather than in memory. Structs cannot be null and must be created on the stack.

While structs are value types in C#, classes are reference types. In other words, when programmers create a new struct instance, it gets created on the stack. When you create a new class instance, it gets created on the heap.

Value types store values in the stack memory. Reference types hold references to objects in memory. Instances of value types are copied into memory when created. In the case of reference types, the reference is copied into memory only when the instance is created.

While the actual instance of the class gets created on the heap memory, you have a reference pointing to it.

Consider the following piece of code that illustrates how you can define a struct in C#:

public struct Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Employee(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }

Classes are reference types and, therefore, must be created on the heap because they hold references to other objects (for example, when you use a class as a base class for another class). Instances of classes are reference types. This means they can be null and are created on the heap.

Consider the following piece of code:

public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Employee(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }

The following code shows how to create a class instance in C#:

internal class Program
{
static void Main(string[] args)
{
Employee employee = new Employee("Joydip", "Kanjilal");
}
}

Read: Class Members in C#

Object Identify vs Value Equality in C#

To determine whether two objects are equal, you must first determine whether they represent the same object in memory or whether certain fields of their values are identical. When comparing values, it is necessary to examine if the objects are value types (structs) or reference types (classes, delegates, arrays).

To check if two instances have the same identity, (i.e., they refer to the same location in the memory), use the Object.Equals method. To check if two struct instances, (i.e., two instances of a struct) have the same values, use the ValueType.Equals method. It should be noted that all value types extend System.ValueType.

Objects are different from primitives (or primitive data types), in that primitives have their own identity. This means that two primitive objects can have the same value but still be distinct from each other. In C#, the object identity is determined by the reference of an object.

Now consider the following class:

public class MyClass
{
    public int X { get; set; }
 }

You can check if two instances of this class are equal using the following C# code example:

static void Main(string[] args)
{
  MyClass myClass1 = new MyClass();
  MyClass myClass2 = new MyClass();
  myClass1.X = 1;
  myClass2.X = 1;
  bool isEqual = myClass1.Equals(myClass2);
  if(isEqual== true )
  {
       Console.WriteLine("The two instances myClass1 and 
        myClass2 are equal.");
  }
  else
  {
      Console.WriteLine("The two instances myClass1 and 
        myClass2 are not equal.");
   }
 Console.Read();
}

When you run the above piece of code, the following message will be displayed at the console window:

The two instances myClass1 and myClass2 are not equal.

Now, create another instance of the class named MyClass, as shown below:

MyClass myClass3 = myClass2;

If you now check the two instances for equality, you will find that they are equal:

isEqual = myClass3.Equals(myClass2);

Here is the complete source code for your reference:

  public class MyClass
    {
        public int X { get; set; }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            MyClass myClass2 = new MyClass();
            myClass1.X = 1;
            myClass2.X = 1;
            MyClass myClass3 = myClass2;
            bool isEqual = myClass1.Equals(myClass2);
            if(isEqual== true )
            {
                Console.WriteLine("The two instances myClass1 and myClass2 are equal.");
            }
            else
            {
                Console.WriteLine("The two instances myClass1 and myClass2 are not equal.");
            }
            isEqual = myClass3.Equals(myClass2);
            if (isEqual == true)
            {
                Console.WriteLine("The two instances myClass3 and myClass2 are equal.");
            }
            else
            {
                Console.WriteLine("The two instances myClass3 and myClass2 are not equal.");
            }
            Console.Read();
        }
    }

When you execute the above program, the following text will be displayed at the console window:

The two instances myClass1 and myClass2 are not equal.
The two instances myClass3 and myClass2 are equal.

Final Thoughts on Objects in C#

Object-oriented programming (OOP) is a great way to organize and reuse your application’s source code. By creating classes, you can group together related data and methods. And, you can create instances of such classes as needed. In this programming tutorial we talked about objects in C# with relevant code examples.

You can learn more about Object-oriented programming in C# by reading our tutorial: C# Object Oriented Programming.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read