Lect 25-26 (Introduction To CSharp)
Lect 25-26 (Introduction To CSharp)
class Hello
{
static void Main() {
Console.WriteLine("Hello world");
}
}
namespace System.Collections
{
public class Stack
{
Entry top;
i 123
s "Hello world"
int total = 0;
Int32 x = 10;
while(x--)
DoSomething();
// try-finally
try{
return;
}
finally {
Console.WriteLine("Code in finally blocks always runs");
}
}
Output
cp CPoint
10
20
object
MemoryStream FileStream
i 123
o System.Int32
123
j 123
public MyForm() {
okButton = new Button(...);
okButton.Caption = "OK";
okButton.Click += new EventHandler(OkButtonClick);
}
c:\windows\Microsoft.NET\Framework\v3.5\bin\csc.exe /t:exe
/out:MyApplication.exe MyApplication.cs
Or
CSC ApplicationName.cs
DEPARTMENT OF COMPUTER SCIENCE, UET TAXILA
using System;
class Square_Root
{
static void Main(string[] args)
{
double a,root;
do
{
Console.Write("Enter a number: ");
a=Convert.ToDouble(Console.ReadLine());
if (a<0)
Console.WriteLine(“Enter a positive number!");
} while (a<0);
root=a/2;
double root_old;
do
{
root_old=root;
root=(root_old+a/root_old)/2;
} while (Math.Abs(root_old-root)>1.0E-6);
Console.WriteLine("The square root of " + a + " is " + root);
}
} DEPARTMENT OF COMPUTER SCIENCE, UET TAXILA
DEPARTMENT OF COMPUTER SCIENCE, UET TAXILA
Writing applications in C#
We can see that everything in a C# application is in a class
In this case the class defines a program entry point Main
◦ This makes the application binary an executable
Note the use of the System namespace
◦ Classes referred to, such as Console and Math, are actually
System.Console and System.Math
class App{
public static void Main(){
Application.Run(new MenuForm());
}
}
class MenuForm:Form{
public MenuForm(){
this.ContextMenu = new ContextMenu(SetupMenu());
this.Menu = new MainMenu(SetupMenu());
}
MenuItem[] SetupMenu(){
MenuItem file = new MenuItem("&File");
file.MenuItems.Add("Exit", new EventHandler(OnExit));
MenuItem messages = new MenuItem("&Message Boxes");
EventHandler handler = new EventHandler(OnMessageBox);
messages.MenuItems.Add("Message Box 1", handler);
messages.MenuItems.Add("Message Box 2", handler);
return new MenuItem[]{file,
DEPARTMENT OFmessages};
COMPUTER SCIENCE, UET TAXILA
void OnExit(Object sender, EventArgs args){
this.Close();
}
return root;
}
} DEPARTMENT OF COMPUTER SCIENCE, UET TAXILA
Writing applications in C#
class Square_Root
{
static void Main(string[] args)
{
double a,root;
do
{
Console.Write("Enter a number: ");
a=Convert.ToDouble(Console.ReadLine());
if (a<0)
Console.WriteLine("Please enter a positive number!");
} while (a<0);
root=Square_Root_Class.calcRoot(a);