Class and object
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.
- Box b1;
- b1 is called a reference variable (not object)
- now b1 is null
- Box b2 = new Box();
- now b2 points box object
- Box b3 = new Box();
- b3.length = 10;
- b3.width = 20;
-
- b1 = b3;
now both b1 and b3 both points to same memory location..if any one updated then another one automatically updated.
Sample code
- namespace ConsoleApplicationdemo {
- class Program {
- static void Main(string[] args) {
- Box b1;
- Box b2 = new Box();
- Console.WriteLine("b2 object length:{0}", b2.length);
- Console.WriteLine("b2 object width:{0}", b2.width);
- Box b3 = new Box();
- b3.length = 10;
- b3.width = 20;
- Console.WriteLine("b3 object length:{0}", b3.length);
- Console.WriteLine("b3 object width:{0}", b3.width);
- b1 = b3;
-
-
- Console.WriteLine("after assigning b3,the b1 object length:{0}", b1.length);
- Console.WriteLine("after assigning b3,the b1 object width:{0}", b1.width);
-
- b3.length = 45;
- b3.width = 55;
- Console.WriteLine("Modified b3 object length:{0}", b3.length);
- Console.WriteLine("Modified b3 object width:{0}", b3.width);
- Console.WriteLine("after modify b3,the b1 object length:{0}", b1.length);
- Console.WriteLine("after modify b3,the b1 object width:{0}", b1.width);
-
- b1.length = 70;
- b1.width = 80;
- Console.WriteLine("Modified b1 object length:{0}", b1.length);
- Console.WriteLine("Modified b1 object width:{0}", b1.width);
- Console.WriteLine("after modify b1,the b3 object length:{0}", b3.length);
- Console.WriteLine("after modify b1,the b3 object width:{0}", b3.width);
- Console.ReadKey();
- }
- }
- class Box {
- public int length;
- public int width;
- int height;
- }
- }
Output
b2 object length:0
b2 object width:0
b3 object length:10
b3 object width:20
after assigning b3,the b1 object length:10
after assigning b3,the b1 object width:20
Modified b3 object length:45
Modified b3 object width:55
after modify b3,the b1 object length:45
after modify b3,the b1 object width :55
Modified b1 object length:70"
Modified b1 object width:80
after modify b1,the b3 object length:70
after modify b1,the b3 object width:80