Monday, November 24, 2008
C# Constructor(s)
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?
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#
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
-------------------------------------------------
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#
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
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:
-------------------------------------------------
<>
{
//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
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..
Wednesday, June 4, 2008
Loops used in C# .net
Loops we use in C# are:
- while Loop,
- do...while Loop
- for Loop and
- foreach Loop
C# while Loop
While loop and do..while loops are used in conditions like the Number of iterations are Unkown ie, the number of times the loop should work is unknown. While loop works only if the Condition gets true.
Let's check the structure of a while loop...
----------------------------------
while(condition==true)
{
//Statements
}
----------------------------------
While loop only works if the Condition is true. Here in this case if the condition doesnt gets false it will become an infinite loop.
C# do ... while loop
-----------------------------------
while loop have a disadvantage that it dosnt gets executed even for one time if the condition is false. To overcome this problem we have do while loop.
do...while loop is also like a while loop but it gets into the loop for the first time even if the condition is false. But from the second time if the loop wants to work the while condition checks for the condition to become true.
The structure of a do...while loop is...
----------------------------------
do
{
//Statements
}while(Condition==true);
----------------------------------
Here from the second time it works only if the Condition or the testexpression becomes true..... In this loop also the number of iterations is not Known.
C# for loop....
For loop is used when the number of iterations is fixed. If we know how many times the loop needs to work we use the For Loop.
The structure of a for loop is...
----------------------------------
for(initialisation;testexpression;increment/decrementoperator)
{
//statements
}
----------------------------------
Here in this case the initialisation is the place we declare or define some values to the variables which should be used inside the loop...
Testexpression checks the condition of the loop ie it defines the number of iteration of the Loop...
increment/decrement This is used to make the condition of the loop to become false so the loop gets stopped at certain interval.
I'll show you an example to get the first ten numbers...
----------------------------------
for(int i=1;i<=10;i++)
{
Console.WriteLine(i);
}
----------------------------------
The above loop will print the first ten numbers. Here itself if we loop at it we can see the Initialisation as int i=1. This is I am declaring a variable with the name i and setting its value as 1. In the second expression I have given a Condition asking whether the variable i have the value less than or equal to 10 and in the third case when each time the loop works the value of variable i gets added by 1. So when it becomes 11 the loop gets terminated.
Working of a for loop...
----------------------------------
While we use a for loop... the initialisation expression is only called for the first time. When the loop starts to run from the second time it doesn't enter to the Initialisation expression instead it increments the value of the variable and checks whether the test expression is true or false.
Step 1: Initialisation
Step 2: Condition
Step 3: Increment or Decrement
For the first time it calls STEP 1
then goes to the Step 2 and enters into the loop body
From the second time when it comes to the loop it goes to Step 3 and then to Step 2..... and if it returns true it enters the loop body...
C# foreach loop...
foreach loop is a new loop introduced in C#. This loop is same as for loop but this loop will be commonly used for working with arrays collections etc.. If we are using a for loop for displaying the values of an array we need to know the size of the array. But in the case of a foreach loop the size of the array need not be known. foreach loop automatically takes the size of the array and calculates it....
Let's see an example for that...
----------------------------------
foreach(DataType var in DataTypeCollection)
{
//Statements
}
----------------------------------
In this type of loop we will be creating a variable which will be the same as the collection datatype to be worked with. If you are going to print all elements of an array collection then the variable should be on the DataType that can store the value of the Array. Like this we can run this for loop even for Controls in .net like ListBox, ComboBox etc.....
Just check how it works.....
----------------------------------
char[] arr=new char[10];
//I need to print all the elements in this array for doing that we can use a foreach loop
for(char c in arr)
{
Console.WriteLine(c);
}
----------------------------------
Here in the above case it will create a Character variable "c" and when the loop starts to work each time it will assign value at the appropriate index to the variable and print it....
Tuesday, May 20, 2008
Conditional Operators in C#
if-else constructor is used to check conditions using. if-else will be always having two conditions True or False.
Let's see a simple if-else constructor.
--------------------------------------
if(Condition)
{
// true part;
}
else
{
// false part;
}
---------------------------------------
In the above set of code we are using an if-else constructor to check a condition. Now if the Condition we have typed inside the if is TRUE it will get inside the True part of the constructor and if the condition is false it will enter inside the false part. The CONDITION may Contain operators like Arithmetic, Relational and Logical for checking different types of conditions.
Now, Lets check a real problem with if-else....
I have two integer variables nameley iNum1 and iNum2. I am going to check which number is bigger.
----------------------------------------
//Assigning values for the two variables
iNum1=10;
iNum2=20;
//Starting the condition
if(iNum1>iNum2)
{
Console.WriteLine("The condition is TRUE");
}
else
{
Console.WriteLine("The condition is FALSE");
}
----------------------------------------
Here iNum1 is assigned a value of 10 and iNum2 is assigned a value of 20. Now when the program gets executed the condition will be returning false because iNum1 variable is smaller than iNum2.
So, it will print "The condition is FALSE" on the screen.
Like this if the condition gets true it will enter into the true part ie the "if" body of the program and if condition gets false it enters into the else part of the Program.
We can also have multiple nested if conditions on a single if-else constructor. Let's check another example of checking which number is bigger out of three numbers.
I have three variables namely iNum1,iNum2,iNum3.
------------------------------------------
if(iNum1>iNum2 && iNum1>iNum3)
{
Console.WriteLine("iNum1 is the biggest number");
}
else if(iNum2>iNum1 && iNum2>iNum3)
{
Console.WriteLine("iNum2 is the biggest number");
}
else
{
Console.WriteLine("iNum3 is the biggest number");
}
------------------------------------------
Here in the above code we are using Relational and Logical operators. When we have multiple conditions like this we can use operators as shown above.
We have actually three conditions here so we can use Nested if's like this. When the if condition gets false it will enter the else if condition and when and only else if condition gets false it will enter the else condition of the program.
This is how we use if-else constructor in programs.
-------------------------------------------------------------
switch-case conditions.
switch case conditional statements are used to check conditions according to the incoming values to the variables. Here we will switch a variable and inside the cases we will check for the conditions.......
Let's see and example for this...
--------------------------------------------------------------
switch(iMonth)
{
case 1:
{
Console.WriteLine("January");
break;
}
case 2:
{
Console.WriteLine("February");
break;
}
case 3:
{
Console.WriteLine("March");
break;
}
default:
{
Console.WriteLine("Please enter a Valid number");
break;
}
}
------------------------------------------------------------
Here in the above code we are switching a variable inside the switch body. Now the switch will check for cases with the value inside the switch variable. If it matches any of the value inside any case it will get into the Case body.
If we pass a value 2 into the variable iMonth the switch will get into the case 2: and print "February".
Since we are using integer Datatype we can straight away write the numbers in the cases with a single space seperated.
The "default" statement gets printed in the case if a number(value) which is not the case conditions is assigned to the switch variable.
Now if you are passing a Character Datatype you must write the cases like this...
--------
case 'A':
{
//statements
break;
}
case 'C':
{
//statements
break;
}
---------
and in the case of strings you can write the cases like this....
---------
case "C#.net"
{
Console.WriteLine("Windows programming");
break;
}
case "ASP.net"
{
Console.WriteLine("Web Programming");
}
---------
you must have checked "break" statements after each case and default statements.
We must use break statements inside this just because it may jump into next Case. In C# break statements are compulsory and if we dont use break statements it will return an error.
We can have multiple cases in the switch statement but only a single default statement in the switch statement....
That's all about switch case and If else conditions.........
Tuesday, March 18, 2008
What are operators?
We have four types of operators in C#.
- Arithmetic Operators,
- Relational operators ,
- Logical operators and
- Unary operators.
Arithmetic Operators :-
Arithmetic Operators are used to do mathematical operations
The basic arithmetic Operators are
+ for addition
- for subtraction
* multiplication
/ division
% modulo operator(This operator is used to return the Remainder of two numbers).
Relational Operators:-
Relational operators are mainly used for checking conditions between two or more variables.
The relational operators we use in C# are..
> Greater than(Checks which number is greater)
<>= Greater than or equal to(Checks whether the given number is greater than or equal to the second number)
<= Less than or equal to(Checks whether the given number is less than or equal to the second number) == Equal to(Checks whether the second number is equal to the first number) != not equal to(Checks whether the second number is not equal to the first number) Logical Operators :
Logical operators are used to check logical conditions with a block of two or more relations
Logical operators we use in C# are AND, OR and NOT.
- AND operator is represented with && (two ampersand)
- OR operator is represented with || (two pipes) and
- NOT operator is represented with !(Exclamation).
eg:-
((iNum1>iNum2) && (iNum1!=0))
In the above example we are checking whether the first variable is greater than the second variable AND iNum1 is not equal to ZERO. Here if both the conditions are true only the condition will execute.
How Logical operators work.
AND(&&)
&&(AND) operator becomes true only if all the conditions are true. If any of the conditions are false && operator returns false.
OR(||)
||(OR) operator becomes false only if all conditions are false. If any of the condition becomes true || operator becomes true.
NOT(!)
!(NOT) operator becomes true if the condition is false and false if the condition is true.
Unary Operators
Unary operators are used to add or subtract a variable by 1.
We have mainly two types of unary operators
Increment and
Decrement.
Increment operator is represented by ++ and decrement operator is represeted by --.
Increment operator adds a variable by one and decrement operator subracts a variable value by
one.
i++, i--.
Unary operators can be used in two ways POSTFIX and PREFIX.
In a postfix notation the unary operator will be placed after the variable(i++)
In a prefix notation the unary operator will be placed before the variable(++i)
Assignment Operator
An assignment operator is used to assign a value to a variable. An = (equal to) symbol is known as an assignment operator.
int i=10;
means assigning the integer variable i a vlaue of 10.
What is a Variable?
Variable will be having a memory address value
For eg:-
int iNum1
char cName
float fNum etc..
Here, int,char,float represents the Data type to be used and iNum1,cName,fNum are the variable names given for those DataTypes.
Rules For Declaring a Variables :-
- A Variable name Should Start with an Alphabet
- Key Words representing the program should not be used as variable name.
- for eg: numeric, int, console etc.. should not be used.
- Special characters except an underscore( _ ) are not allowed
- Variable names should not start with a number.
Friday, March 7, 2008
Data Types in C#
Now we will check some other programs in C#.
What do you mean by a Data Type?
In simple words Data Type means the type of data. The data may be mainly of three types. They are
Integer, Character and Float. These are also called base data types.
Integer are used to store integers or numbers without decimals.
eg:- 1,123,1452,9999 etc...
Characters are used to accept letters. Basically a character Data type can accept only one byte. So, it will store only one Letter.
eg:- a,A,b,c,d etc....
If we write -AB- it will return an error...
Float is used to accept Floating numbers or numbers with decimals..
eg:- 1.8F,21.3F etc
Some data types are :-
Name. . . . . Description
byte . . . . .. . 8-bits '
sbyte . . . .. . 8-bits
int. . . . . . . .. 32-bit
uint. . . . . . .. 32 bit
short. . . . . ..16-bit
ushort . . . .. 16-bit
long. . . . . . .. 64-bit
ulong. . . . . .. 64-bit
float . . . . . .. 32-bit
double. . . . .. 64-bit
decimal . . . . 96-bit
bool . . . . . . . true and false
char. . . . . . . 16-bit
Tuesday, March 4, 2008
First Program in C#
Now we can see a simple program in C#.
-------------------------------------------------
using System;
namespace smilu
{
class cHello
{
public static void Main(string[] args)
{
Console.Write("Hello World");
}
}
}
--------------------------------------------------------
I know that if you are a fresher to C#; you may be wondering seeing the Code. There is nothing in much in the above code....
Let's be now familiar with what is written in the above code.
In the above code go from the begining...
The first line is
using System;
The using statement is used to add a NAMESPACE into this program.
Namespaces are collection of Classes. These Namespaces are used to avoid Class Name Conflicts. ie, there may be situations where we must have two or more CLASSes with the same Name. So, inside a program, it will not allow to create two classes with the same name. So there exists a problem. So to avoid these types of conflicts we use Namespaces. So we create a namespace and add the classes inside the namespace and we create the other class with the same name in another namespace.
In the above program we have added System namespace into this program. The System namespace contains CLASSes for implementing base datatypes.
Now the second step
namespace smilu
This step is used to create a User Defined namespace which contain classes. Here we have created a Namespace in the name of "smilu".
Then you must have noticed curly brackets throughout this program. These are the Bodies of Namespace, Classes and Functions.
The Third step
class cHello
As I have said in the earlier topics that C# is an Object Oriented Language. So an Object Oriented Language(OOL) must have a class. Without class we cannot say a program is purely Object Oriented(refer). So, in this step we are creating a CLASS with name "cHello".
We will be writing rest of the Codes inside the CLASS
The Fourth Step
public static void Main(string[] args)
or
public static void Main()
This is the most important Function of a Program. Without the Main() function a program will not Execute. We write the Main() function in C# like this. All the things written there are not necessary. We will check each keyword in the Declaration.
public:
public written in the function refers it Access to others.It is known as "Access Specifier" ie we have Given a public access to the Main function,so anywhere within the program we can access this function.
Static:
C# is an OOL. So member variables and member functions can only be accessed through objects. Here in the case of Main it is the heart of a program. When we execute a program the first thing which gets executed is the Main() function. This is the first class so Object for this class can only be created inside the Main() function. So we must have to get the program started by executing the Main() function. That is why we declare a Static keyword to Main() function. So it is not necessary to create object for the class.
void:
void means NOTHING.... void represents the return type of the Main() function. ie, what the main should return to the program. Here in this case we doesn't need anything to be returned.. so, we have given the return type as void.
Main(string[] args) :
string[] args is used to store Command Line Arguments(if any). Command Line Arguments are arguments which we pass to a program while its execution with its Name.
The Fifth Step
Console.Write("Hello World");
Here we are creating Console application ie, we create a DOS based program. System.Console is a class which contains definitions for Write(), Read() etc... We mainly use
Write(); For writing in the same line(output)
WriteLine() This is used to Write in a string and set a break to the Line after that.
Read() Read a single line
ReadLine() Reading the strings.
Here in the above code inside the write function I have written "Hello World". The text inside the double quotes("") represenets the text to be printed as the output. What all we are write inside the "" of the Write() or WriteLine() functions will be printed as that itself exept some Escape charactors like...
Commonly used escape charactors are...
\n - For new Line
\t - For a Tab Space
\b - For a BackSpace etc...
NOTE:- C# is a case sensitive Language. So it is necessary that you write codes in appropriate cases itself as written above.
After you type the program save the file with a Filename with extension ".cs"(eg:- Hello.cs).
For executing the program take the Microsoft Visual Studio 2005 Command Prompt from
START->PROGRAMS->MICROSOFT VISUAL STUDIO 2005->MICROSOFT VISUAL STUDIO TOOLS->MICROSOFT VISUAL STUDIO 2005 COMMAND PROMPT.
Now navigate to the Folder you have saved the File.
Compile the Code.
For Comiling you have to do like this .. if the file name is Hello.cs
In the COmmand prompt write " csc Hello.cs " and Press enter
If the compilation returns Successfully write the File name and press Enter
like
" Hello " and Enter.
You will get an output as
Hello World
Saturday, March 1, 2008
What is Object Oriented Programming?
Object Oriented Programming was first introduced in 1960’s.The main reason behind this programming is to make the program user friendly. OOP concept is related to the real-world system (i.e concept of Classes and Objects).
What is a CLASS?
Class is just a Virtual concept of a collection of related items together which we cannot see or feel.In programming we create Classes to define collection of related variables and functions.
Class is a user defined Data Type
What is an Object?
In simple words -- Object is an Instance of a Class. We can access a Class only through its Objects.Without objects we cannot say a Class is existing.A thing which has the properties of a class is known as Objects.
For eg:- Car is a Class and Tata Indica is an Object of the class Car
Objects….
If we take a car Indica its state is its color, wheel, body, etc….
Its Behavior is moving, changing gears etc…
And the identity of the car is its Number lets say KL-7 AD 2544.
Here state and behavior may be same for many objects but the identity of object will not be same for other object.
Characteristics of OOProgramming…
The main characteristics of Object Oriented Programming are:-
- Inheritance
- Encapsulation
- Abstraction
- Polymorphism
INHERITANCE
The ability of a class (Derived Class) to derive or Inherit the properties of another class (Base Class) is called Inheritance.Inheritance helps in the reusability of code hence making the program smaller and easy to use.
Eg:- Parent child relationship. Child is Inherited from its parents
ENCAPSULATION
Process of Hiding the data from a user is called Encapsulation; also called Data Hiding.
ABSTRACTION
The process of showing essential features without giving any explanations is known as Abstraction.
POLYMORPHISM
The name Poly Morphism means Many Forms. It is the process by which we create same things with different behaviors.
Eg:- Function overloading…
Eg Same person behaving in different ways. Make the person you teach as the example and ask him whether he behaves like the same when he is in front of his Principal and friend…. You can change the principal to Police also so the student will really understand what is poly morphism.
Wednesday, February 27, 2008
Types of Application
You should be aware what is a program. What all are the key factors in a program...
So first lets start with the Basics.....
We all are creating Applications. So lets check what all are the functions performed by an Application.
The functions performed by an application can be divided into three categories
- User services
- Business services and
- Data Services
User Services layer constitutes the front end of the solution. It is also called the Presentation Layer because it provides the interactive user interface.
The business services layer controls the enforcement of business rules on the data of an organization.
Business rules encompass those practices and activities that define the behavior of an organization.
The data services layer comprises of the data and the functions for manipulating this data.
Applications may vary from Single-tier desktop applications to multi-tier applications (two, three or n-tier architecture).
SINGLE-TIER Architecture
In a single-tier architecture a single executable file handles all functions relating to the user, business and data service layers. Such an Application is also called Monolithic applications.
TWO-TIER Architecture
The tow-tier architecture divides an application into two components:-
Client - Implements the user interface
Server - Stores Data
In case for this architecture the user and data services are located separately either on same machine or in separate machine.
THREE-TIER Architecture
In case of Three-Tier architecture all the three service layers reside Separately, either on the same machine or on different machine. The user interface interacts with the Business logic. Business logic validates the data sent by the interfaces and forwards it to the database if it confirms to the requirement.
n-TIER Architecture
An n-tier application uses business objects for handling business rules and data access. It has multiple servers handling business services. This application architecture provides various advantages over other types of application architectures. The advantages include extensibility, resilience to change, maintainability and scalability of the application.
Tuesday, February 26, 2008
Welcome
Regards
SMilu