What is the Object in C#

Now we are going to learn about the definition of the object in C#.
  • 2467

Introduction

An object in a class is a collection of the related method or variables. A variable is like for example if you make a house then house is a class and walls are objects and bricks as like the method of the class. Basically object is a block of memory that has been allocated according to the class requirement. The syntax for declaring an object is like this.

className objectName= new  ClassName();
E.g.: Sample objSample=newSample();

Example of the object:
 

public
class Person
{
public
string Name { get; set; }
 public int Age { get; set; }
public
Person(string name, int age)
{
Name = name;
Age = age;
}
}
class
Program
{
static
void Main()
{
Person
person1 = new Person("Leopold", 6);
Console
.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
Person
person2 = person1;
person2.Name = "Molly";
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);
Console
.WriteLine("Press any key to exit.");
Console
.ReadKey();
}
}
}

Output:

objects.jpg

© 2020 DotNetHeaven. All rights reserved.