Вы находитесь на странице: 1из 28

Classes and Objects

Defining a class
It is a user-defined data type with a template that serves to define its properties. After definition, create variables : instances of classes, which are the actual objects. Class classname { Variables declaration; Methods declaration; } It include many more items such as properties, indexers, constructors, destructors and operators Classes and structs are very similar, but class is a reference type. Class include more features compared to structs.

Constructors Member initialization The this reference Nesting of Classes Constant Members Read-only Members Properties Indexers

overloaded constructors static constructors private constructors copy constructors destructors

Initial values must be assigned for the object which is created. Two approaches: uses the dot operator to access the instance variables and then assigns values to them individually. Takes the help of a function like GetData to initialize each object individually rect1.getData(15,10)

C# supports a special type of method, called a constructor. It enables an object to initialize itself when it is created. Constructors have the same name as the class itself. They do not return any value.

class Rectangle { public int length; public int width; public Rectangle(int x, int y) // constructor method { length=x; width=y; } public int Rectarea() { return(length*width); } }

Class RectangleArea { public static void Main() { Rectangle rect1=new Rectangle(15,10);//Calling Constructor int area1=rect1.RectArea(); Console.WriteLine(Area1=,+area1); } }

Constructors are usually public because they are provided to create objects. They can also be declared as private or protected, then the class cannot be used as a base class for inheritance. This property may be used in the implementation of inheritance.

Overloaded Constructors
It is possible to create methods that have the same name, but different parameter lists and different definitions. [method overloading] matches up the method name ,the number & type of parameters to decide which one of the definitions to execute.[polymorphism] Extend the concept of method overloading to provide more than one constructor to a class.

class Room { public double length; public double breadth; public Room(double x, double y) // constructor { length=x; length=y; }

public room(double x) //constructor 2 { length=breadth=x; } Room room1= new Room(25.0,15.0) public int Area() // using constructor1 { room2= new Room(20.0) return (length*breadth); Room // using constructor2 }

Static Constructors
A static constructor is called before any object of the class is created. It is usually used to assign initial values to static data members. A static constructor is declared by prefixing a static keyword to the constructor definition. It cannot have any parameters.

class Abc { static Abc() // no parameters { . // set values for static members here There is no access modifier on static } constructor. }

It cannot take any. A class can have only one static constructor.

Private constructors
C# does not have global variables or constants. All declarations must be contained in a class. Such classes are never required to instantiate objects. Creating objects using such classes may be prevented by adding a private constructor to the class.

Copy constructors
A copy constructor creates an object by copying variables from another object. Pass an item object to the Item constructor so that the new Item object has the same values as the old one. C# does not provide a copy constructor, provide it ourselves if we wish to add this public Item(Item item) The copy constructor is invoked by {code=item.code; instantiating an object of type Item and passing it the object to be copied price=item.price; Item item2=new Item(item1); Item2 is a copy of item1. }

Opposite to a constructor It is a method called when an object is no more required. Name of the destructor is the same as the class name Preceded by a tilde.(~) Class fun { ~fun() // no arguments { } } C# manages the memory dynamically and uses a garbage collector; The process of calling destructor when an object is reclaimed by garbage collector is called finalization.

Member initialization
C# also allows us to assign initial values to individual data members at the time of declaration. class initialization { int number=100; static double x=1.0; string name= john; . } Static variables are assigned when the class is loaded. Static variables are initialized to their default values when the class is loaded. Thus a variable is never uninitialized in C#.

Constant members
C# permits declaration of data fields of a class as constants. This can be done using the modifier const public const int size =100; public const int size; //compilation error const members are implicitly static. public static const int size=100; //wrong & compile time error

Decide the values of a constant members at run time. class Numbers { public readonly int m; public static readonly int n; public numbers(int x) { m=x; } static numbers() { n=100; }

Read Only Members

The methods to set or retrieve the values of members. GetData() & SetData() using System; Class Number { private int number; public void SetNumber(int x) // accessor method { number =x; //private number accsessible } public int GetNumber() // accessor method { return number; }}

class NumberTest { public static void Main() { Number n= new Number(); n.SetNumber(100); Console.WriteLine(Number = +n.GetNumber()); //n.number Output of program } Number=100 }

The SetNumbers method is also known as the mutator method. Code the accessor methods manually. Users have to remember that they have to use accessor methods to work with data members. properties [same as accessor methods] It is much more elegant and simple to use.

Implementing a property
Using system; Class Number { private int number; public int Anumber { get { return number; } set { number=value; } } }

// property

class PropertyTest { public static void Main() { Number n= new Number(); n.Anumber=100; int m=n.Anumber; Console.WriteLine(Number =+m); } }

A property that has only a getter is called a readonly property. A property that has only a setter is called writeonly property. Get clause uses code to calculate the value of the property using other fields and returns the results. Properties are inheritable. Abstract, virtual, new, override Static modifier can be used.

Location indicators and are used to access class objects. Two difference: The indexer takes an index argument and looks like an array. The indexer is declared using the name this. public double this[int idx] {get{ //return desire data} set{// set desire data} } }

Property and Indexers

Property can be static member, whereas A get accessor of property corresponds to a method with no parameters.

an indexer is always an instance member. a get accessor of an indexer corresponds to a method with the same formal parameter list as the indexer. Set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer, plus the parameter named value.

A set accessor of a property corresponds to a method with a single parameter named value.