Monday, March 3, 2008

How to use Operators in C#?

_____________________________________________

How to use Operators in C# ?

_____________________________________________

Comparison
== < > <= >= !=

Arithmetic
+ - * /
% (mod)
/ (integer division if both operands are ints)
Math.Pow(x, y)

Assignment
= += -= *= /= %= &= |= ^= <<= >>= ++ --


____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

How to use loops statement in C# ?

_____________________________________________

How to use loops statement in C# ?

_____________________________________________

Pre-test Loops:

// no "until" keyword
while (c < 10)
c++;

for (c = 2; c <= 10; c += 2)
Console.WriteLine(c);



Post-test Loop:

do
c++;
while (c < 10);



// Array or collection looping
string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
Console.WriteLine(s);

// Breaking out of loops
int i = 0;
while (true) {
if (i == 5)
break;
i++;
}

// Continue to next iteration
for (i = 0; i < 5; i++) {
if (i < 4)
continue;
Console.WriteLine(i); // Only prints 4
}


____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

How to use if statement in C# ?

_____________________________________________

How to use if statement in C#?

_____________________________________________

greeting = age <>? "What's up?" : "Hello";

if (age < greeting = "What's up?">else
greeting = "Hello";

// Multiple statements must be enclosed in {}
if (x != 100 && y <>

No need for _ or : since ; is used to terminate each statement.





if
(x > 5)
x *= y;
else if (x == 5)
x += y;
else if (x <>else
x /= y;



// Every case must end with break or goto case
switch (color) { // Must be integer or string
case "pink":
case "red": r++; break;
case "blue": b++; break;
case "green": g++; break;
default: other++; break; // break necessary on default
}


____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Namespaces of C#

_____________________________________________

Namespaces of C#.

_____________________________________________

namespace Harding.Compsci.Graphics {
...
}

// or

namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}

using Harding.Compsci.Graphics;

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

File I/O of C#

_____________________________________________

File I/O of C#.

_____________________________________________

using System.IO;

// Write out to text file
StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();

// Read all lines from text file
StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();

// Write out to binary file
string str = "Text data";
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();

// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();


____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Constructors / Destructors of C#

_____________________________________________

Program Structure in C#.

_____________________________________________

class SuperHero {
private int _powerLevel;

public SuperHero() {
_powerLevel = 0;
}

public SuperHero(int powerLevel) {
this._powerLevel= powerLevel;
}

~SuperHero() {
// Destructor code to free unmanaged resources.
// Implicitly creates a Finalize method
}
}


____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Program Structure in C#

_____________________________________________

Program Structure in C#.

_____________________________________________

End Namespace using System;

namespace Hello {
public class HelloWorld {
public static void Main(string[] args) {
string name = "C#";

// See if an argument was passed from the command line
if (args.Length == 1)
name = args[0];

Console.WriteLine("Hello, " + name + "!");
}
}
}

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Delegates / Events of C#

_____________________________________________

Delegates / Events of C#.

_____________________________________________

delegate void MsgArrivedEventHandler(string message);

event MsgArrivedEventHandler MsgArrivedEvent;

// Delegates must be used with events in C#


MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message"); // Throws exception if obj is null
MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);



using System.Windows.Forms;

Button MyButton = new Button();
MyButton.Click += new System.EventHandler(MyButton_Click);

private void MyButton_Click(object sender, System.EventArgs e) {
MessageBox.Show(this, "Button was clicked", "Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Enumerations of C#

_____________________________________________

Enumerations of C#.

_____________________________________________

enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
Console.WriteLine(a + " is " + (int) a); // Prints "Stop is 1"

Console.WriteLine((int) Status.Pass); // Prints 70
Console.WriteLine(Status.Pass); // Prints Pass

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Console I/O of C#

_____________________________________________

Console I/O of C#.

_____________________________________________

Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
// or
Console.WriteLine(name + " is " + age + " years old.");


int c = Console.Read(); // Read single char
Console.WriteLine(c); // Prints 65 if user enters "A"

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Using Objects of C#

_____________________________________________

Using Objects of C#.

_____________________________________________

SuperHero hero = new SuperHero();


// No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;

hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method



SuperHero hero2 = hero; // Both reference the same object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name); // Prints WormWoman

hero = null ; // Free the object

if (hero == null)
hero = new SuperHero();

Object obj = new SuperHero();
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");

// Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) {
string line;
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
}

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Exception Handling of C#

_____________________________________________

Exception Handling of C#.

_____________________________________________

// Throw an exception
Exception up = new Exception("Something is really wrong.");
throw up; // ha ha

// Catch an exception
try {
y = 0;
x = 10 / y;
}
catch (Exception ex) { // Argument is optional, no "When" keyword
Console.WriteLine(ex.Message);
}
finally {
// Requires reference to the Microsoft.VisualBasic.dll
// assembly (pre .NET Framework v2.0)
Microsoft.VisualBasic.Interaction.Beep();
}

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Structs of C#

_____________________________________________

Structs of C#.

_____________________________________________

struct StudentRecord {
public string name;
public float gpa;

public StudentRecord(string name, float gpa) {
this.name = name;
this.gpa = gpa;
}
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;

stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Properties of C#

_____________________________________________

Properties of C#.

_____________________________________________

private int _size;

public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}


foo.Size++;

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

String of C#

_____________________________________________

String of C#.

_____________________________________________

Escape sequences
\r // carriage-return
\n // line-feed
\t // tab
\\ // backslash
\" // quote



// String concatenation
string school = "Harding\t";
school = school + "University"; // school is "Harding (tab) University"

// Chars
char letter = school[0]; // letter is H
letter = Convert.ToChar(65); // letter is A
letter = (char)65; // same thing
char[] word = school.ToCharArray(); // word holds Harding

// String literal
string msg = @"File is c:\temp\x.dat";
// same as
string msg = "File is c:\\temp\\x.dat";

// String comparison
string mascot = "Bisons";
if (mascot == "Bisons") // true
if (mascot.Equals("Bisons")) // true
if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.CompareTo("Bisons") == 0) // true

Console.WriteLine(mascot.Substring(2, 3)); // Prints "son"

// String matching
// No Like equivalent - use regular expressions

using System.Text.RegularExpressions;
Regex r = new Regex(@"Jo[hH]. \d:*");
if (r.Match("John 3:16").Success) // true

// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");

// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer); // Prints "one TWO three"

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Comments of c#

_____________________________________________

Comments of C#.

_____________________________________________

// Single line
/* Multiple
line */
///

XML comments on single line
/*XML comments on multiple lines */

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Arrays of C#.

_____________________________________________

Arrays of C#.

_____________________________________________

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]);


// 5 is the size of the array
string[] names = new string[5];
names[0] = "David";
names[5] = "Bobby"; // Throws System.IndexOutOfRangeException


// C# can't dynamically resize an array. Just copy into new array.
string[] names2 = new string[7];
Array.Copy(names, names2, names.Length); // or names.CopyTo(names2, 0);

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[3][] {
new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Functions of C#

_____________________________________________

Functions of C#.

_____________________________________________

// Pass by value (in, default), reference (in/out), and reference (out)
void TestFunc(int x, ref int y, out int z) {
x++;
y++;
z = 5;
}

int a = 1, b = 1, c; // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5

// Accept variable number of arguments
int Sum(params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}

int total = Sum(4, 3, 2, 1); // returns 10

/* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
Console.WriteLine("Greetings, " + prefix + " " + name);
}

void SayHello(string name) {
SayHello(name, "");
}

____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Classes / Interfaces of C#

_____________________________________________

Classes / Interfaces of C#.

_____________________________________________

Accessibility keywords
public
private
internal
protected
protected internal
static

// Inheritance
class FootballGame : Competition {
...
}


// Interface definition
interface IAlarmClock {
...
}

// Extending an interface
interface IAlarmClock : IClock {
...
}


// Interface implementation
class WristWatch : IAlarmClock, ITimer {
...
}


____________________________________________________________________

Note:Applicable for .net also asp.net.
____________________________________________________________________

Data Types of C#.

_____________________________________________

Data Types of C#.

_____________________________________________


Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime (not a built-in C# type)

Reference Types
object
string

Initializing
bool correct = true;
byte b = 0x2A; // hex

object person = null;
string name = "Dwight";
char grade = 'B';
DateTime today = DateTime.Parse("12/31/2007 12:15:00");
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265;
long lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
uint uiTotal = 123;
ulong ulTotal = 123;

Type Information
int x;
Console.WriteLine(x.GetType()); // Prints System.Int32
Console.WriteLine(typeof(int)); // Prints System.Int32
Console.WriteLine(x.GetType().Name); // prints Int32

Type Conversion
float d = 3.5f;
int i = (int)d; // set to 3 (truncates decimal)

____________________________________________________________________

Note:Applicable for .net also asp.net.

____________________________________________________________________

What is .NET ?

What is Microsoft.NET platform?

Microsoft .NET is a software development platform based on virtual machine based architecture. Dot net is designed from the scratch to support programming language independent application development. The entire .NET programs are independent of any particular operating system and physical hardware machine. They can run on any physical machine, running any operating system that contains the implementation of .NET Framework. The core component of the .NET framework is its Common Language Runtime (CLR), which provides the abstraction of execution environment (Physical machine and Operating System) and manages the overall execution of any of the .NET based program.





With dot NET, Microsoft introduces a completely new architecture for Windows applications (WinForm), Data Access (ADO.NET), Web Applications (ASP.NET), Windows components (Assemblies), Distributed Applications (.NET remoting), and above all the XML based Web Services. The famous figure for the representation of dot net is presented below: