WORKING WITH VISUAL STUDIO
3) Allocates the required memory for execution of the class.
Constructor
1) It is a special method that is available to every class responsible for initializing the variables of a class 2) Every class requires a Constructor in it. If at all it has to execute. Without a Constructor any class can't execute.
Note: - Because Constructors are mandatory for a class to execute when the program is getting
compile. The compiler if doesn't finds a Constructor in that class will take the responsibility of defining a Constructor to the class.
If we write a class as following and compile
class Test {
int x;string s;bool b; }
after compilation it looks as following
class Test {
public Test( ) //Constructor {
x=0; str=null; b=false; }
}
Compile define Constructor will always be "public". A Constructor will have the same name of your class and moreover they are non-value returning methods.
syntax to define a Constructor
We can define Constructor in a class as following.
[<modifiers>] <name> ([<param def>]) {
stmts }
*Add a class "ConDemo.cs" in the project and write the following code
{
ConDemo() {
Console.WriteLine("Constructor of class"); }
void Demo() {
Console.WriteLine("Method of class"); }
staticvoid Main() {
ConDemo cd1 = new ConDemo();
ConDemo cd2 = new ConDemo();
ConDemo cd3 = cd2;
cd1.Demo(); cd2.Demo(); cd3.Demo();
Console.ReadLine(); }
}
In the above program each time we create an object of the class it will internally invoke the Constructor of that class, which is then responsible for allocation of the Memory required class.
Constructors are of two types
1) Zero Argument (or) Default Constructors 2) Parameterized Constructors
A Constructor without any parameters is a Zero argument of Default Constructor where as a Constructor with parameter is a parameterized constructer.
If a class contains parameterized Constructors in it values to the parameters has to be sent while creating the object of a class. Because a Constructor call should always match a Constructor signature.
To check this rewrite the Constructor in out above class as following.
ConDemo(int x) {
Console.WriteLine("Constructor of class:"+x); }
Now if we run the class we will get an error. Because our Constructor call is not matching the
Constructor signature. To resolve the problem pass values to the Constructor while creating the object under Main as following.
ConDemo cd1=new ConDemo(10); ConDemo cd2=new ConDemo(20);
Constructors are used in a class for initializing variables of a class. So using a parameterized Constructor we can send all the initialization values that are required for a class to execute. To test this add a new class "Maths.cs" in your project and write the following code.
{
int x, y; //Class Variables public Maths(int x, int y) //Block Variables
{
this.x = x;
this.y = y; }
public void Add() {
Console.WriteLine(x + y); }
public void Sub() {
Console.WriteLine(x - y); }
public void Mul() {
Console.WriteLine(x * y); }
public void Div() {
Console.WriteLine(x / y); }
staticvoid Main() {
Maths obj = new Maths(200, 25);
obj.Add(); obj.Sub(); obj.Mul(); obj.Div();
Console.ReadLine(); }
}
In the above program, the class requires some initialization value for the Methods to execute, which are sent to a class using Constructor only.
Defining a class that can be used for performing transactions in an ATM Machine.
public class Constructor {
int custid; double bal;
public Constructor(int custid) {
this.custid=custid;
bal=<load balance from database for given id>; }
public double GetBalance() {
return bal; }
public void Withdraw(double amt) {
bal=-amt;
//Update balance to database for given id }
{
bal=+amt;
//Update balance to database for given id }
}
Assume the details of the Customers are present in the banks database as following.
Customers
Custid Cname Bal 101 xxx 5000 102 yyy 10000 103 zzz 15600
Our above class customer requires a key value for execution that is customerid, whenever a customer’s accesses the machine with his ATM card the customerid is red from the card and an "object" gets
created for the class.
Any number of customers can access the database at the same time, so internally for each customer one object gets created on the server and associated with the client.
Customer c1=new Customer(101); Customer c2=new Customer(102); Customer c3=new Customer(103);
Here each object created for the customer initializes the data associated with the customer as following.
As every customer is associated with a separate object and we are aware that manipulations
performed on the members of an object doesn't reflect to members of other object. So transactions performed by a customer will affect his data only.
Assume the first two customers are performing two transactions as following
c1.Deposit(3000); c2.Withdraw(3000);
Now internally the data will be as following
As we are aware a class is a collection of members like variables, methods, Constructors etc. These members will be of two different categories.
1) Non-static (or) Instance Methods 2) Static members
The members of a class which requires the object of a class for initialization or execution are known as Instance members where as members of a class which do not require object of a class for initialization or execution are known as static members.
Instance variables Vs Static Variables
1) A variable under a static block or a variable declared using static modifier are static variables, rest of all are instance variables only
Eg: - int x=100; }--> instance statc int y-100; }--> static
static void Main() { |
int z=100; |--> static } |
2) The initialization of a static variable gets done, if we execute the class in which the variable is declared whereas instance variable gets initialized after creating the object of class either within the class or in other class also.
3) The minimum and maximum number of times a static variable gets initialized will be one and only one time whereas in 'n' case of instance it will be '0' if no objects are created or 'n' if 'n' objects are created.
Note:-To access an instance member we use object of the class whereas to access static members we use name of the class.
We use Instance variables if at all we want any value that is a specific to an object.
Eg:- Customerid and balance in our previous class Customer where as we use static variable if we want any value that should be common for the complete class.
Constant Variables
It is a variable which contain a fixed value that cannot be modified while declaring a constant at the time of declaration only we need to assign values to it. The behaviour of a constant variable will be the same as the behaviour of Static variable. Only difference is static variables can be modified but
constant variables cannot be modified.
ReadOnly Variables
These are very much similar to constants whose values cannot be modified after initialization but their behaviour will be similar to Instance variables which are initialized when the object is created and also maintains a separate copy for each object.
A Constant value (Variable) is a fixed value for the complete class where as ReadOnly variable is a fixed value specific for each object.
Note: - A ReadOnly variable can be initialized either under constructor or at the time of declaration.
*Add a class “StatVars.cs” and write the following. class StatVars
{
int x = 100; //Instance staticint y = 100; //Static
public const float pi = 3.14f; //Constant public readonly bool flag; //ReadOnly public StatVars(bool flag)
{
this.flag = flag; }
staticvoid Main() {
Console.WriteLine (StatVars.y);
Console.WriteLine (StatVars.pi);
StatVars s1 = newStatVars (true);
StatVars s2 = newStatVars (false);
Console.WriteLine (s1.x + " " + s2.x);
Console.WriteLine (s2.flag + " " + s2.flag);
Console.ReadLine (); }
} }
Static Methods Vs Instance Methods
A Method declared using static modifier is a static method. Rest of all are Instance objects while defining static methods make sure we are not consuming any non static members of the class directly from static methods we need to consume them only using object of the class where as the reverse is possible directly.
Note: - Non-Static members of a class cannot be consumed from static blocks of a class directly they need to be consumed using class objects.
*Add a class “StatMets.cs” and write the following code. class StatMets
{
int x = 100;
staticint y = 200;
staticvoid Add() {
StatMets obj = newStatMets();
Console.WriteLine(obj.x + y); }
staticvoid Main() {
StatMets.Add();
Console.ReadLine(); }