Start C# here

Study C#.. Go ahead ! !

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.

Monday, July 28, 2008

Methods with return type in C#

Here in this topic we will check how we can create Methods with a return type.

We use methods with a return type when we need a method to return some values to the place from which the method has been called. Return type can be of any type. If we need to return and Integer we can use int keyword. Likewise we can return string, float, double, Class etc...

While we create a method with a return type it should have the keyword "return" followed by the value of the type the method returns...
If the method is returning an integer we can write it as return 0. Because 0 is an integer.

Let's check an example for methods with a return type...
-----------------------------------------
Example 1:-
------------
//Method with an integer return type
public int Add()
{
int iResult=10+20;

return iResult;
}
------------
Here we have used the return keyword to return the value inside the integer variable iResult. So if we call the method Add() we will be getting the sum of the two numbers.

Example 2:-
------------
//Method with a string return type
public string HelloWorld()
{
return "Hello World!";
}
------------
In the above example we have created a method with a string return type. Here we are returning the string "Hello World!".
-----------------------------------------

While we call a method with a return type it should also be stored into the same type. Like wise we can create method(s) with return types.



Now we'll see methods with parameters that return values.


Parameters are used inside a method to pass values to a method at the time of call. We must specify the types of variables inside the method parenthesis for accepting values. Parameters which we declare inside the method parenthesis is also known as Function signatures. While we pass values to methods which accepts values, it should be passed in the exact order in which we have defined that method.

Let's check a method with parameters:-
-----------------------------------------

class Calculator
{

public int AddNumber(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}

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

Here AddNumber is the name of the method. Since the access specifier is public, the method can be accessed from outside the class also. The method is taking two integers as the parameters and returning the value stored in the result variable. So, we must have to pass two integer values while we call this method. The values passed to this method will be stored in num1 and num2 variables.

eg:-

static void Main(string[] args)
{
int iResult=AddNumber(10,20);
Console.WriteLine(i);
}

Here we have called the method AddNumber. Since the method returns an integer it is assigned to an integer variable. Likewise we should do in each function which have return type..

C# Functions/Methods

A function/method is a set of one or more program statements, which can be executed by referring to the function/method name.

When a complex application is divided into methods, code becomes more flexible, easy to maintain and to debug. For performing repetitive tasks methods are useful. Methods allow breaking an application into discrete logical units, which makes the application more readable. Code written in a method can be reused since it can be executed any number of times by calling the method itself with little or no modification.

The syntax of defining a method is given below:
-------------------------------------------------

<> (Parameter list)
{
//Method body
}

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

Let's look at an example:
-------------------------------------------------


public void Hello()
{
Console.WriteLine("Hello World!");
}

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

Here "public" keyword shows the access to this method/function. When we use public access specifier the method can be accessible inside and outside the class.

"void" refers to the return type of the method. Void means nothing should be returned and Hello() is the function/method name. Functions/methods will be having opening and closing parenthesis.

Wednesday, July 23, 2008

C# Array

Arrays are collection of Elements having the same DataType stored in Consecutive memory locations. Arrays can only store data of the same type ie, if it’s an integer array the array can only store Integer values. It will not allow any other types to be stored.

Let’s see how we can declare an array in C#.

If you need to create a character array to store ten elements then we can declare it like this…

char[] cArr=new char[10];

To pass values to an Array at the time of declaration we can write an array like this…

char[] cArr={‘H’,’e’,’l’,’l’,’o’,’!’};

Since this is a character array we can only pass single values.

We’ll now see how we create arrays for each type..

Integer Array in C#
--------------------

int[] iArr=new int[10];
or
int[] iArr={1,2,3,4,5};

String Array in C#
-------------------
string[] sArr=new string[10];
or
string[] sArr={“Hello”,”world”};

In an array.. items are stored in index of the array. For retrieving values in an array we must mention the index. Always the first index of an array will be 0 and the last index will be the size of the index minus 1 ie if the size is 10 for an array the last index will be 9.

In the above case of the string array the values “Hello” and "World" will be stored in two index of the array. The index of the “Hello” will be 0 and “World” will be 1.
If we need to just print hello on the screen then we must have to write..

Console.WriteLine(sArr[0]);

Here in the above code sArr is the Array name and 0 is used to mention the Element in which index should be selected likewise if we need to print World then we must have to say sArr[1]..

Now we will check how we can print all items in an Array. For doing this we can use two types of loops.
The first one is for loop…

For loop to display Elements in an Array
-----------------------------------------

for(int i=0;i
{
Console.WriteLine(sArr[i]);
}

Here in the above case we have written int i=0 in the for loop and for printing we have just written it sArr[i] here we says I because its having the values from 0 to the value less than the length of the array.

So, when the loop works for the first time its value will be 0 so it prints “Hello” and when it goes for the second time the value is 1 so it prints “World” and when it goes for the third time the value is not less than 2 ie the length is two for the array and now the value of I is also two so it terminates…..

When we use for loop it have a drawback ie we must know the size of the array. For curing that we have another loop ie foreach loop in c#.

In a foreach loop its not necessary to know the size of the array…
We’ll just see one foreach loop for the same array…

Foreach loop to display items in an array..
-------------------------------------------

foreach(string s in sArr)
{
Console.WriteLine(s);
}

In the above code we are using foreach loop if just see the two loops itself we can see the difference. In a Foreach loop we don’t need to mention the array size to be printed…. When we run the foreach loop it will store the first element in string variable s and prints it and next time it will automatically gets incremented to the next element and prints the second element…. Likewise it will run till the array terminates..