C# object

object is the instances of a class or struct. For example, if we assume human as a class, then you will be an object of human class. C# is an Object Oriented Programming language.

class human
{
public int age;
public string sex;
public human(int a, string s) {age=a;sex=s;}
public string isex
{
get
{
return sex;
}
set
{
sex = value;
}
}
}
human James = new human(28,"male"); //James is an object of class human

To get and set the sex property of object James:
James.isex = "female"; //set sex to female
System.Console.Write(James.isex); //female

Objects can be used as a variable, or an element of array or collections.
human Mary = new human(26,"female");
human[] arr = new human[] {James,Mary};
//----------------------------------
using System.Collections.Generic;
List<human> lst = new List<human> {James,Mary};

struct object:
public struct classmate
{
public string name;
public string sex;
public string knowsex
{
get { return sex;}
set { sex = value;}
}
public string classmate(int n, string s)
{
name = n;
sex = s;
}
}
classmate Jacobs = new classmate("Jacobs","male");


Although both struct object and class object can be created by new operator, because structs are value types, a new struct object can also be created by copy. While class objects are reference types, the copy of a class object has a reference to the same address as the original one. Which means if you change the property of the copy object, the property value of the original object will be changed too.

classmate Jacobs = new classmate("Jacobs","male"); //Jacobs is a struct object
classmate Sophia = Jacobs;
Sophia.knowsex = "female";
System.Console.WriteLine(Jacobs.sex); //male, unchanged
//-------------------------------------
human James = new human(28,"male"); //James is an object of class human
human Mary = James;
Mary.isex = "female";
System.Console.WriteLine(James.sex); //female, changed


endmemo.com © 2024  | Terms of Use | Privacy | Home