Start C# here

Study C#.. Go ahead ! !

Saturday, June 13, 2009

Destructor in C#

C# Destructors are used to destroy an object of a Class. Destructors are automatically invoked when the Scope of the Object goes out. We represent a Destructor with a tilde(~) symbol. Destructor will also be having the Same name of the class.
If there is a class with the name "Hello" we can represent its destructor as
~Hello()

Destructors cannot be overloaded, Inhertied or have Modifiers defined to it.
we can see a Simple program..

-------------------------------------------------
using System;

namespace Destructorss
{
class One
{
//Constructor
public One()
{
Console.WriteLine("First Constructor Called");
}

//Destructor
~One()
{
Console.WriteLine("First destructor is called.");
}
}

class Two : One
{
//Constructor
public Two()
{
Console.WriteLine("Second Constructor Called");
}
//Destructor
~Two()
{
Console.WriteLine("Second destructor is called.");
}
}

class Three : Two
{
//Constructor
public Three()
{
Console.WriteLine("Third Constructor Called");
}
//Destructor
~Three()
{
Console.WriteLine("Third destructor is called.");
}
}

class MyDestructor
{
static void Main()
{
Three t = new Three();
}

}
}

/*The result of this Program will be:-
First Constructor Called
Second Constructor Called
Third Constructor Called

Third destructor is called.
Second destructor is called.
First destructor is called.
*/

-------------------------------------------------

In the above program we have constructors and Destructors. Constuctors invoke from the First to the Third while Destructors go just in the Opposite way ie it starts from Third destrucor and goes to First....

Monday, November 24, 2008

C# Constructor(s)

what are Constructors?

Constructors are methods that gets automatically invoked when an object of a class is created. Constructors are used to Initialize values to variables inside the class automatically at the time of object creation.
Constructors will be having the same name of the class itself. Constructor doesn't return any value.

Let's see an example for Constructor..

-------------------------------------
using System;

class HelloWorld
{
int iNum1,iNum2;
string sName,sAddress;

//Creating a Constructor
public HeloWorld() //Line1
{
iNum1=iNum2=0;
sName="";
sAddress="";
}
}
-------------------------------------

Here, in the above code we have created a default constructor with the name of the class. Constructors will not be having a return type.

The Line1 represents the constructor for the class HelloWorld. The same name of the class itself will be given to constructor also.

We can have multiple constructors inside a class but should be overloaded. We use overloaded constructors for initializing values by passing it to the object of the class.

Eg
-------------------------------------
using System;

class HelloWorld
{
int iNum1,iNum2;
string sName,sAddress;

//Creating a Constructor
public HeloWorld() //Line1
{
iNum1=iNum2=0;
sName="";
sAddress="";
}
//Overloaded constructor
public HelloWorld(int _iNum,string _sName,string _sAddress)
{
iNum1=_iNum; //Line1
sName=_sName;
sAddress=_sAddress;
iNum2=0;
}

}
-------------------------------------

Here, in the above code we have two constructors but our function signatures are different in both Constructors. In the first constructor the Function signature or parameter is void and in the second one we have three parameters one Integer and two strings. So for invoking the second constructor we must have to pass values to the object.

Eg
--------------------------
//Invokes the Default Constructor
HelloWorld hwObj=new HelloWorld();

//This invokes the Second constructor
HelloWorld hwObj1=new HelloWorld(20,"SMILU","TPRA");

--------------------------

Like this we can have many constructors inside a Class.

Now, if in the case we have Static class and variables and have to initialize those variables we need another type of constructors called Static constructors.
Static constructors are used for initializing values inside Static classes. We cannot have instance constructors inside the static classes.

For Creating a static constructor we can use the static keyword.
-----------------------------------------
static class HelloWorld
{
static int i;
static HelloWorld()
{
i=10;
}
}
------------------------------------------

These are the types of constructors in C#.

Thursday, November 6, 2008

What is an Object?

What is an object?
In simple words we can say an Object as an "Instance of a Class." Without Objects we cannot say a Class is Existing.
An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.
Look at the program given below:
using System;

---------------------------------------
namespace prime_no
{
class prime
{
int num;
public void acceptNo()
{
Console.WriteLine("Enter a number:");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
}
public void primeNosTill()
{
int i, j;
bool answer = false;
Console.WriteLine("The prime numbers till entered number are: ");
for (i = 2; i <= num; i++)
{
for (j = 2; j <>
{
if (i % j == 0)
{
answer = true;
break;
}
}
if (answer == false)
Console.WriteLine(i);

else
answer = false;
}
}
class execute
{
public static void Main(string[] a)
{
prime primeNo = new prime();
primeNo.acceptNo();
primeNo. primeNosTill();
Console.Read();
}
}
}
}
---------------------------------------

The prerequisite of object creation is a class i.e. you can only create an object of a class. For the declaration of a class, the class keyword is used. In the above code, class keyword defines the class prime. The braces know as delimiters, are used to indicate the start and end of a class.
The functions of a class are called member functions. A function is a set of statements that performs a specific task in response to a message. Member functions are declared inside the class. The function declaration introduces the function in the class and function definition contains the function code. The two member functions in the above code are acceptNo and primeNosTill.
The execute class is declared with the Main() method. The execute is used as a class from where the prime class can be instantiated. To use the members of the class, the object of that must be created.
The above code contain class prime and the object has been named primeno.
prime primeno = new prime();
The member functions (acceptNo and primeNosTill), can be accessed through the object (primeno) of the class prime using “.” operator.
primeno.acceptNo();
primeno. primeNosTill();

The acceptNo function accepts the number from the user and primeNosTill function displays all the prime numbers till the number entered by the user.

Thursday, July 31, 2008

Access Specifiers in C#

What is an access specifier?

An access specifier defines the scope of a class member. A class member refers to the variables and functions in a class. A program can have many classes. The programmer gets the privilege to decide the of use access specifier to implement encapsulation and abstraction in C#.

So, when we use Access Specifiers in C# they help the other class members to know how they can access the methods or variables declared/defined inside another class.

C# supports five types of access specifiers to tell the extent of visibility of a class member. They are:-
  • public,
  • private,
  • protected,
  • internal and
  • protected internal.

Let's now go into detail.

public:

The public access specifier in C# allows a class to expose its member variables and member functions to other functions and objects. So any member declared public can be accessed outside the class also.

Let's check an example for this..
----------------------------------------------------------------

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
HelloObject.iNum1=10; /* since variable iNum1 is public it can be accessed in other classes also*/

Console.WriteLine(HelloObject.iNum1);
}
}
}

----------------------------------------------------------------

private:

The private access specifier in C# is just opposite to the public access specifier. That is it allows a class to hide its member variables and member functions from other class objects and functions. So it is not visible outside the class. By default, the access specifier is private; if public, private or protected is not specified.

Let's check an example for this..
----------------------------------------------------------------

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
private int iNum2;

public hello()
{
iNum1=0;
iNum2=10;
}
}

class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
//CORRECT METHOD
HelloObject.iNum1=10; //Here since variable iNum1 is public it can be accessed in other classes also

//WRONG METHOD
HelloObject.iNum2=20; /*This line will return an Error since the access to this variable is Private. So it cannot be accessed outside the class*/

Console.WriteLine(HelloObject.iNum1);
}
}
}

----------------------------------------------------------------

protected:

The protected access specifier in C# allows a class to hide its member variables and member functions from other class objects and functions, except the child class. This access specifier is used when we need to use Inheritance in the program.

Let's check an example for this..
----------------------------------------------------------------

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
protected int iNum2;
}

class world : hello
{
public int AddDetails()
{
iNum1=20;
iNum2=10;

return iNum1+iNum2;
}
}

class MyMainClass
{
static void Main(string[] args)
{
world worldObject=new world();

worldObject.iNum1=50; //Line 1 No Error

worldObject.iNum2=10; //Line 2 Error

Console.WriteLine(worldObject.AddDetails().ToString());

}
}
}

----------------------------------------------------------------
In the above case we have not called the object of the class hello. But we have inherited the class hello to the class world. So all the public and protected members inside the class is accessible inside the derived class also. We don't need to create objects for the base class to access the variables or methods we have in our parent class.
Now inside the Main() function we are assigning value to iNum1 and iNum2. Line 1 will not return any error because the variable iNum1 is public. So, it can be accessed from anywhere in the program, but Line2 will give an Compilation Error saying "iNum2 is inaccessible due to protection level". This is because access of the variable iNum2 is set to protected. The protected members can only be accessed inside the Child class and its parent class.


internal:

The internal access specifier in C# allows a class to expose its member variables and member functions to other function and objects. It can be accessed from any class or method defined with the application in which the member is defined. The default access specifier is internal for a class.

protected internal:

The protected internal access specifier in C# allows methods or member variables accessible to a class and its derived classes inside the same assembly or namespace within a file. These members cannot be accessed from class inside another assembly or a file.


Lets now understand the above with an example:
----------------------------------------------------------------
using System;
class Student
{
private string sAddress;
protected string sPhNo;
protected internal long iZipCode;
void Hello()
{
Console.WriteLine(“Hello World!”);
}
internal void Hello2()
{
Console.WriteLine(“Hello Student!”);
}
public void SetAddress()
{
Console.WriteLine(“Enter your Address:”)
sAddress = Console.ReadLine();
}
public void SetPhNo()
{
Console.WriteLine(“Enter your Phone Number:”)
sPhNo = Console.ReadLine();
}
public void SetZipCode()
{
Console.WriteLine(“Enter the Zip Code: “);
iZipCode =Convert.ToInt64(Console.ReadLine());
}
public void DisplayStudent()
{
Console.WriteLine(“The Address is: {0}”, sAddress);
}
}
class Display
{
static void Main(string[] args)
{
Student John = new Student();
Console.WriteLine(John.sPhNo); //Error: Protected members cannot be accessed
John.SetAddress(); //public members can be accessed outside the class definition
John.SetPhNo(); //public members can be accessed outside the class definition
Console.WriteLine(John.iZipCode); //error: protected internal members cannot be accessed outside the class definition
John.SetZipCode(); //public members can be accessed outside the class definition
John.DisplayStudent(); // public members can be accessed outside the class definition
Console.WriteLine(John.sAddress); //error: private members cannot be accessed outside the class definition
John.Hello(); //error: private members cannot be accessed outside the class definition
John.Hello2(); //displays Hello student!
Console.ReadLine();
}
}
----------------------------------------------------------------

That's how access specifiers work.

Wednesday, July 30, 2008

Function Overloading

Function overloading is the process of having the same name for functions but having different parameters(function signatures), either in number or in type. Function overloading reduces the complexity of a program. Function overloading helps the user to use functions without changing its name or the return type. To overload a function we need to change the parameters inside the Function. The parameters/function signature(s) should not be the same for another function which need to overloaded.
-------------------------------------------------
class MethodOverloading
{
//Method one
public void Add(int i, int j)
{
Console.WriteLine(i+j);
}
//Method Two
public void Add(string s, string k)
{
Console.WriteLine(s+k);
}
}
--------------------------------------------------
Here in the above code we have two methods with the same name Add. This method is overloaded since the signatures inside it changes in the second method. In the first method we have passed two Integer values as parameters and in the second method we have passed two string values into the method. Now when we call this method, if we are passing two integer values to the method then the first method will be invoked and will be adding the two integers and showing the result to us. In the other case if we are passing two String values into the same function the second method will be invoked and it will be concatenating the two strings and the concatenated string is displayed.
Here when we used function overloading it does not vary in the return type. But the behavior has changed according to the values we pass to the functions.

In the above case Method 1 and Method 2 have the same return Type but are varied in the signature.
Method 1 has two integer parameter and Method 2 has two string parameters.

Now we’ll check some more examples for function overloading..


class MethodOverloading
{
public int Display(int i)
{
return i;
}


public int Display(int j, int k)
{
return j+k;
}
public int Display(int l, int m,int n)
{
return (l+m-n);
}
}
-------------


Here in the above cases in all the functions we have integer parameters. These are also overloaded because the parameters passed to each method vary in number ie; the First method has only one parameter; the second have two parameters and the third have three parameters.