An introduction to C#
C# is a language that was developed by Microsoft
specifically targeted for the .NET platform.
C# Features
No pointers
Automatic memory management
Completely object-oriented
Supports interface-based programming
Both implementation inheritance and interface
inheritance supported
Support for overloaded operators
Support for aspect-based (attribute-based)
programming
Can only produce managed-code
Lets try a simple program.
Create a Working Directory
mkdir k:\week1\hello
Copy corvars.bat
copy
c:\Program Files\Microsoft Visual Studio.NET
\FrameworkSDK\bin\corvars.bat
k:\week1\hello\corvars.bat
Set up environment, run covars.bat
Cd k:\week1\hello
Type corvars.bat <hit return>
4
Open notepad, create the following file and
save it in the k:\week1\hello directory as
hello.cs.
class Hello
{
static void Main()
{
System.Console.WriteLine("Hello World");
}
}
5
Compile the program
k:\week1\hello>csc Hello.cs
Run the program
K:\week1\hello>Hello.exe
K:\week1\hello> Hello World
C#.NET Language Basics
Types in C#
Defining integer types
A Bit About Strings
Reading From and Writing To The Console
If Then Statement
Looping The For Next Statement
Primitive Types
C# Type
.NET Framework type
bool
System.Boolean
byte
System.Byte
sbyte
System.Sbyte
char
System.Char
decimal
System.Decimal
double
System.Double
float
System.Single
9
Primitive Types (contd.)
int
System.Int32
uint
System.UInt32
long
System.Int64
ulong
System.UInt64
object
System.Object
short
System.Int16
ushort
System.UInt16
string
System.String
10
A word on types
All types in .NET derive from System.Object
They are provided implementations of ToString() and
GetType()
To get a string with the type of any variable, you can
call <var>.GetType()
Whenever you call Console.WriteLine(obj) the
ToString() method on obj is implicitly called. The
default ToString implementation for classes simply
returns the name of the class.
11
What Are Integers
0, 432, -5, 10000000, -10000000
Integers are whole numbers
Integer variables are stored as signed 32-bit
(4-byte) integers ranging in value from 2,147,483,648 through 2,147,483,647.
12
Defining Integers
int i;
int i, j, k;
int i = 12;
j = i; j is now equal to 12
i = 15;
k = i + j; k is equal to 27
To write an Integer, convert it to a String using:
k.ToString();
13
A Bit About Strings
14
What are strings?
abcdef Abcdef aBcdEf A23+-/*789 q
John J. Smith
How do you do?
123 South Street, Calais, ME 04235
Are we there?
an empty string
15
How do we define strings?
string strTmp;
strTmp = time will tell;
string strTmp = time will tell;
strTmp = Console.ReadLine();
string strTmp2;
strTmp2 = strTmp;
strTmp2 time will tell
16
Concatenating Strings
string strCity = Calais;
string strState = ME;
string strZip = 04270;
string strLoc;
strLoc = strCity + , + strState + + strZip;
strLoc Calais, ME 04270
17
Some String Functions
string strTmp;
strTmp.Trim(); removes leading and trailing spaces
strTmp.ToUpper(); converts string to all upper case
strTmp.ToLower(); converts string to all lower case
strTmp.Length; returns string length as an integer
strTmp.SubString() extracts a substring
18
String Function Examples
string strTmp = Hello World
strTmp.Trim();
strTmp Hello World
string strTmp = Hello World;
strTmp.ToLower(); hello world
strTmp.ToUpper(); HELLO WORLD
19
String.Length Function
string strTmp;
strTmp = in the beginning;
The value of strTmp.Length is 16.
int i;
i = strTmp.Length;
The value of i is 16.
20
String.SubString() Function
String.Substring(startIndex , length );
Parameters (are Integers)
startIndex Where the substring starts.
startIndex is zero-based.
length The number of characters in the
substring.
21
Substring Examples
string strTmp;
strTmp = around the world;
strTmp.Substring(0,6); around
strTmp.Substring(11,5); world
strTmp.Substring(0,strTmp.Length);
around the world
22
Writing to the Console
Console.WriteLine(String); write with line return
Console.WriteLine(Hi There)
C:\>Hi There
C:\>
Console.Write(String); write with no line return
Console.Write(Hi There)
C:\>Hi There
23
Reading from the Console
Console.ReadLine(); returns a string
string tmp;
Console.Write(What is your name? );
tmp = Console.ReadLine();
Console.WriteLine(Hi + tmp);
C:\>What is your name? Chip
C:\>Hi Chip
C:\>
24
if Statement
if (some condition is true)
{
do something in here,
using one or more lines of code
}
25
What is difference between = and ==?
= is for assignment of value
String tmpString = Hello world;
int i = 12;
== is for equivalence
if (str1 == str2) { some code }
if (str.Length == 0) { some code }
if (str1 != end) { some code }
26
Sample if Statement
string strInput ;
strInput = Console.ReadLine();
if (strInput == )
{
Console.WriteLine(Input required.);
}
27
The For Loop
28
A Simple For Loop
int i;
for (i = 1; i<10; i++)
{
Console.WriteLine("The value of i is " + i.ToString());
}
The Value of i is 1
The Value of i is 2
The Value of i is 3
The Value of i is 9
The Value of i is 10
29
Or You Could Reverse It
int i;
for (i = 10; i>0; i--)
{
Console.WriteLine("The value of i is " + i.ToString());
}
The Value of i is 10
The Value of i is 9
The Value of i is 8
The Value of i is 2
The Value of i is 1
30
To Walk Through a String
string tmp = hello world;
for (int k = 0; k< tmp.Length-1;k++)
{
Console.WriteLine(tmp.Substring(k,1));
}
31
To Walk Through a String Backward
string tmp = "hello world";
for (int k =tmp.Length-1;k>-1;k--)
{
Console.WriteLine(tmp.Substring(k,1));
}
32
What About?
What If We Want To Enter More Data?
What If No String Is Entered?
What If The Entered String Is Too Long?
How Do We Know When We Are Done?
33
What If We Want To Enter More Data?
Labels
A Label is Defined with a Colon ReturnHere:
goto Statements
goto Statements Direct Program Flow To A Label
goto ReturnHere;
GoTo Statements are Evil and High Risk!!!
34
What If No String Is Entered?
Checking for a zero length string.
if (tmpStr.Length == 0)
{
Console.WriteLine(No String Entered);
goto ReturnHere;
}
Note: You could also check for tmpStr ==
35
What If The Entered String Is Too Long?
Lets only work with strings up to 10 characters
if (strTmp.Length > 10)
{
strTmp = strTmp.SubString(0,10);
}
36
How Do We Know When We Are Done?
Lets check for the string end to end the program
if (strTmp == end)
{
return;
}
Note: return tells the program to exit the subroutine, which in this
case will end the program.
37
Comments in C#
Both /* */ and // can be used for comments.
VS provides comment/uncomment selections.
Use the menu bar, or Ctrl-K Ctrl-C for comment and CtrlK Ctrl-U for uncomment
38
39
Now lets redo hello.cs as a
Visual Studio project.
40
Visual Studio.NET
The newest version of Visual Studio
Multiple language development finally in one
environment.
Can program in
Visual C#
Visual Basic.NET
Visual C++.NET
Can build
Desktop console and GUI applications
Web services
ASP.NET Web applications
Mobile applications
41
To get Visual Studio.NET
You need to purchase either:
An MSDN subscription
A copy of Visual Studio.NET
Academic editions are available (in or through the
bookstore ?)
42
Visual Studio.NET
Start up Visual Studio.NET
Open a new project by either:
In Visual C# Projects, create a Console
Application
Implement the Main() method
Clicking on the New Project button on the Start Page
OR
File-> New-> Project from the Menu Bar
Notice you now have IntelliSense
Add the Console.WriteLine line of code.
Compile using the Build menu.
Run using the Debug menu
43
Your code should look like this
using System;
namespace HelloVS
{
/// <summary>
/// Summary description for App.
/// </summary>
class App
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
System.Console.WriteLine("Hello World");
}
}
}
44
Class Exercise (time permitting)
Using the Visual Studio.NET write an interactive console
program to accept information from the keyboard and
then format and display the information back. It might be
a persons name and address or a variable list of favorite
pets including name and type of animal or whatever.
Focus on formatting the data, looping to accept multiple
entries, testing for missing information and also testing
for an at end condition. A sample, somewhat simplified
example is in the Class Collections zip file on the web
(i.e. www.PondviewSoftware.com).
45
46
Homework Part 1
Send Me An Email ChipSchopp@comcast.net, include the
following:
1.
Full Name, Nick Name, Student ID #
2.
Home Phone / Work Phone
3.
Email Address (s) [email gives me one]
4.
Your background in computing/programming
5.
Any experience with .NET, other courses, ?
6.
Your objective or goals for this course
7.
Any material you have a special interest in covering?
8.
Any issues or questions that you have?
9.
Which additional dates you would attend classes on.
47
Homework Part 2
C#.Net Programming
Homework Assignment Week 1
Assignment Due: November 13, 2003 5:30 PM
48
Write a C#.NET Console Application, which
performs the following:
Accepts a first name string, a middle name string, and a last name string from
the console. The first name and last name are required. The middle name is
optional.
2.
Concatenates the two or three fields together creating a full name string.
3.
Truncates the full name to 20 characters if the length of the full name is
longer than 20 characters.
4.
Provides the capability of displaying the full name either vertically or
horizontally and forward or backward as desired.
5.
Allows the full name field to be displayed in either of these four ways as
many times as desired.
6.
Allows the user to go back to the top and start over, entering a new name.
7.
Terminates gracefully.
Note:
There was enough information discussed in todays class to complete this
assignment. Feel free to use any additional commands, structures, or
49
functions you wish.
1.
50