C# Tutorial: by Hanumantha Rao.N
C# Tutorial: by Hanumantha Rao.N
C# Tutorial: by Hanumantha Rao.N
By
Hanumantha Rao.N
C# Tutorial
C#
Not all of the supported languages fit entirely neatly into
the .NET framework, but the one language that is
guaranteed to fit in perfectly is C#.
C# (C Sharp), a successor to C++, has been released in
conjunction with the .NET framework.
C# design goals:
05/05/15
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
Variable Types
C# is a type-safe language. Variables are declared as
being of a particular type, and each variable is
constrained to hold only values of its declared type.
Variables can hold either value types or reference types,
or they can be pointers.
A variable of value types directly contains only an object
with the value.
A variable of reference type directly contains a reference
to an object. Another variable many contain a reference
to the same object.
It is possible in C# to define your own value types by
declaring enumerations or structs.
05/05/15
www.hanutechvision.jimdo.com
Possible Values
sbyte
System.sbyte
Yes
-128 to 127
short
System.Int16
Yes
-32768 to 32767
int
System.Int32
Yes
231 to 231 - 1
long
System.Int64
Yes
263 to 263 - 1
byte
System.Byte
No
0 to 255
ushort
System.Uint16
No
0 to 65535
uint
System.Uint32
No
0 to 232 - 1
ulong
System.Uint64
No
0 to 264 - 1
float
System.Single
Yes
double
System.Double
Yes
decimal
System.Decimal
Yes
12
char
System.Char
N/A
05/05/15
bool
www.hanutechvision.jimdo.com
System.Boolean
N/A
1/2
true or false
Value Types
Value Types: int x = 10;
Reference Types: New reference types can be defined using 'class',
'interface', and 'delegate' declarations
object.
object x = new object();
x.myValue = 10;
Pointers
A pointer is a variable that holds the memory address of
another type. In C#, pointers can only be declared to
hold the memory addresses of value types.
Pointers are declared implicitly, using the dereferencer
symbol *. The operator & returns the memory address
of the variable it prefixes.
Example: What is the value of i?
int i = 5;
int *p;
p = &i;
*p = 10;
www.hanutechvision.jimdo.com
Pointers
To address the problem of garbage collection, one can
declare a pointer within a fixed expression.
Any value types declared within unsafe code are
automatically fixed, and will generate compile-time errors
if used within fixed expressions. The same is not true for
reference types.
Although pointers usually can only be used with value
types, an exception to this involves arrays.
A pointer can be declared in relation to an array, as in the
following:
int[] a = {4, 5};
int *b = a;
Arrays
Single-dimensional arrays have a single dimension
int[] i = new int[100];
Enumerations
An enumeration is a special kind of value type limited
to a restricted and unchangeable set of numerical values.
When we define an enumeration we provide literals
which are then used as constants for their corresponding
values. The following code shows an example of such a
definition:
public enum DAYS { Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday};
enum byteEnum : byte {A, B};
Enumerations
using System;
public class EnumTest {
public enum DAYS: byte
{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday};
public static void Main() {
Array dayArray = Enum.GetValues(typeof(EnumTest.DAYS));
foreach (DAYS day in dayArray)
Console.WriteLine("Number {1} of EnumTest.DAYS is {0}",
day, day.ToString("d"));
}
}
05/05/15
www.hanutechvision.jimdo.com
Enumerations
Console.WriteLine("Number {1} of EnumTest.DAYS is {0}",
day, day.ToString("d"))
is equivalent to:
Console.WriteLine(String.Format("Number {1} of
EnumTest.DAYS is {0}", day, day.ToString("d")));
Operators
C# has a number of standard operators, taken from C, C+
+ and Java. Most of these should be quite familiar to
programmers.
To overload an operator in a class, one defines a method
using the operator keyword. For instance, the following
code overloads the equality operator.
public static bool operator == (Value a, Value b) {
return a.Int == b.Int
}
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
Loop Statements
while loops
while (expression) statement[s]
do-while loops
do statement[s] while (expression)
for loops
for (statement1; expression; statement2) statement[s]3
foreach loops
foreach (variable1 in variable2) statement[s]
int[] a = new int[]{1,2,3};
foreach (int b in a)
System.Console.WriteLine(b);
05/05/15
www.hanutechvision.jimdo.com
Namespaces
Namespaces can be thought of as collections of classes;
they provide unique identifiers for types by placing them
in an hierarchical structure.
To use the System.Security.Cryptography.AsymmetricAlgorithm
class, specify it in the following statement:
using System.Security.Cryptography;
An alias for the namespace can be specified as using
myAlias = System.Security.Cryptography;
For instance, the following code states that the class
Adder is in the namespace fred.math.
namespace fred {
namespace math {
public class Adder { // insert code here }
}
}
05/05/15
www.hanutechvision.jimdo.com
Class Declaration
www.hanutechvision.jimdo.com
Class Declaration
There are seven different - optional - class modifiers.
Four of these public, internal, protected, and private
are used to specify the access levels of the types
defined by the classes.
The public keyword identifies a type as fully accessible to all
other types.
If a class is declared as internal, the type it defines is
accessible only to types within the same assembly (a selfcontained 'unit of packaging' containing code, metadata etc.).
If a class is declared as protected, its type is accessible by a
containing type and any type that inherits from this containing
type.
Where a class is declared as private, access to the type it
defines is limited to a containing type only.
05/05/15
www.hanutechvision.jimdo.com
Class Declaration
The permissions allowed by protected internal are
those allowed by the protected level plus those
allowed by the internal level.
The new keyword can be used for nested classes.
A class declared as abstract cannot itself be instanced it is designed only to be a base class for inheritance.
A class declared as sealed cannot be inherited from.
05/05/15
www.hanutechvision.jimdo.com
Class Declaration
The class base part of the class declaration specifies the
name of the class and any classes that it inherits from.
The following line declares a public class called
DrawingRectangle which inherits from the base class
Rectangle and the interface Drawing:
public class DrawingRectangle : Rectangle, Drawing
www.hanutechvision.jimdo.com
Methods
Methods are operations associated with types.
int sum = Arithmetic.addTwoIntegers(4, 7);
A method declaration, specified within a class
declaration, comprises a method-head and a methodbody.
The method-head is made up of the following elements
(square brackets enclose those which are optional).
[attributes] [method-modifiers] return-type methodname ([ formal-parameter-list] )
Method attributes work in a similar way to those for
classes.
05/05/15
www.hanutechvision.jimdo.com
Methods
There are ten method modifiers that can be used. Four
of these are the access modifiers that can be used in class
declarations. These four work analogously to the way
they work in class declarations. The others are the
following:
Abstract: A method without specifying its body. Such methods
are themselves termed abstract. A class contains an abstract
method it cannot be instantiated.
The static modifier declares a method to be a class method (a
method that can be invoked without an instance).
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
www.hanutechvision.jimdo.com
Delegates
using System;
using System.Threading;
public class Ticker
{
private int i = 0;
public void Tick(Object obj)
{
Console.WriteLine("tick " + ++i);
}
}
public class DelegateExample
{
static void Main(string[] args)
{
Ticker ticker = new Ticker();
TimerCallback tickDelegate = new TimerCallback(ticker.Tick);
new Timer(tickDelegate, null, 0, 500);
Thread.Sleep(5000); // The main thread will now sleep for 5 seconds:
}
}
05/05/15
www.hanutechvision.jimdo.com
Input/Output
using System;
using System.IO;
class DisplayFile
{
static void Main(string[] args)
{
StreamReader r = new StreamReader(args[0]);
string line;
Console.Write("Out File Name: ");
StreamWriter w = new StreamWriter(Console.ReadLine());
while((line = r.ReadLine()) != null) {
Console.WriteLine(line);
w.WriteLine(line);
}
r.Close();
w.Close();
}
}
05/05/15
www.hanutechvision.jimdo.com
Exceptions
The exception handling in C#, and Java is quite similar.
However, C# follows C++ in allowing the author to
ignore more of the exceptions that might be thrown (an
exception which is thrown but not caught will halt the
program and may throw up a dialogue box).
To catch a particular type of exception in a piece of code,
you have to first wrap it in a try block and then specify a
catch block matching that type of exception.
When an exception occurs in code within the try block,
the code execution moves to the end of the try box and
looks for an appropriate exception handler.
05/05/15
www.hanutechvision.jimdo.com
Exceptions
For instance, the following piece of code demonstrates
catching an exception specifically generated by division
by zero:
try {
res = (num / 0);
catch (System.DivideByZeroException e) {
Console.WriteLine("Error: an attempt to divide by zero");
}
}
www.hanutechvision.jimdo.com
Exceptions
using System;
public class ExceptionDemo {
public static void Main () {
try {
getException();
} catch (Exception e) {
Console.WriteLine("We got an exception");
}
finally {
Console.WriteLine("The end of the program");
}
}
public static void getException() {
throw new Exception();
}
www.hanutechvision.jimdo.com
} 05/05/15
Code Documentation
The C# compiler supports the automatic creation of class
documentation.
Where the equivalent functionality for Java produces HTML,
the C# documenter produces XML.
This means that the C# documentation is not as immediately
ready to use as the Java documentation.
However, it does allow there to be different applications which
can import and use the C# documentation in different ways.
(Note: using Visual Studio you can also create HTML
documentation, but we will not be covering this here).
To document any element in a C# script, you precede the element
with XML elements. Each of the lines comprising this
documentary code should be marked off as comments using the
following special comment indicator (you can compare this with
the
standard comment indicators).
05/05/15
www.hanutechvision.jimdo.com
Code Documentation
The following code gives an example of how one can
provide overview information about a class.
/// <summary>
/// The myClass class represents an arbitrary class
/// </summary>
public class myClass
Generating C# Documentation
You tell the compiler to produce documentation when
compiling by invoking it with the switch: /doc:file
In this switch, file represents the name of the file that you want
the documentation written to. As the documentation is
generated in xml format, the file should have the extension
.xml. So, for instance, to produce the documentation for a
program in sys.cs file in a file named my.xml, we would use
05/05/15
the command: csc www.hanutechvision.jimdo.com
sys.cs /doc:my.xml
TcpListener(IPAddress, Port):
AcceptTcpClient - a blocking method that returns a
TcpClient you can use to send and receive data. Start - Starts
listening for incoming connection requests.
AcceptSocket - a blocking method that returns a Socket you
can use to send and receive data.
Close - Closes the www.hanutechvision.jimdo.com
listener.
05/05/15
NetworkStream
int Read (byte[] buffer, int offset, int size) - Reads
data from the NetworkStream.
Write (byte[] buffer, int offset, int size) - Writes data
to the NetworkStream.
Close - Closes the
NetworkStream.
05/05/15
www.hanutechvision.jimdo.com
UdpClient Constructor:
public UdpClient( AddressFamily family );
public UdpClient( int port );
public UdpClient( IPEndPoint localEP );
public UdpClient( int port, AddressFamily family );
public UdpClient( string hostname, int port );
IPEndPoint: Initializes a new instance of the IPEndPoint class.
public IPEndPoint( long address, int port )
public IPEndPoint( IPAddress address, int port );
05/05/15
www.hanutechvision.jimdo.com
05/05/15
www.hanutechvision.jimdo.com