C# SHARP PresentationCS 151 Spring 2001. |
|
|
Introduction |
C# (pronounced "C-sharp") is a new Java-like software programming language recently submitted by Microsoft to the ECMA standards group.
This statement is from Microsoft: "C# is a modern, object-oriented language that enables programmers to quickly build a wide range of applications for the new Microsoft .NET platform, which provides tools and services that fully exploit both computing and communications."
June 26, 2000 -- Microsoft announced the new Java-like programming language to the ECMA standards group.
Why C# ? |
C# seems to be a reply to the Sun
Microsystems from Microsoft that they can develop a better language than
Java ( It's not sure yet ). But C# is a Java like language. By using C#
developers can develop web programs and web services easier than other
Microsoft tools such as VC++ and Visual Basic.
Main Goals: |
The main design goal of C# was simplicity rather than pure power. You do give up a little processing power, but you get features like type safety and automatic garbage collection in return.
C# can make
your code more stable and productive.
And offers several key benefits for programmers:
·
Simplicity
·
Consistency
·
Modernity
·
Object-orientation
·
Type-safety
·
Version support
·
Compatibility
·
Flexibility
Object Oriented! |
C# ditches multiple inheritance in favor of native support for the COM+ virtual object system.
Encapsulation
Polymorphism
Inheritance
C# ditches the entire concept of global functions, variables, and constants.
Instead, you can create static class members, making C# code easier to read and less prone to naming conflicts.
And speaking of naming conflicts, have you ever forgotten that you created a class member and redefined it later on in your code? By default, C# methods are nonvirtual, requiring an explicit virtual modifier. It's far harder to accidentally override a method, it's easier to provide correct versioning, and the vtable doesn't grow as quickly. Class members in C# can be defined as:
private
public
protected
internal.
You
retain full control over their encapsulation.
Methods and operators can be overloaded in C#, using a syntax that's a lot
easier than the one used by C++. However, you can't overload global
operator functions—the overloading is strictly local in scope. The
overloading of method F below is an example of what this looks like:
The COM+ component model is supported through the implementation of
delegates—the object-oriented equivalent of function pointers in C++.
Interfaces support multiple inheritance. Classes can privately implement internal interfaces
through explicit member implementations, without the consumer ever knowing
about it.
Code
Examples: |
The canonical “Hello, world” program can be written in C# as follows:
using System;
class Hello
{
static void
Main() {
Console.WriteLine("Hello, world");
}
}
The default file extension for C# programs is .cs, as in hello.cs. Such a program can be compiled with the command line directive
csc hello.cs
which produces an executable program named hello.exe. The output of the program is:
Hello, world
Close examination of this program is illuminating:
What to download |
1) You will need Windows 98 or above OS.
2) You will need Internet Explorer 5.5
3) Download and install .NET Framework SDK Technology Preview
4) Now you should look at some of the samples Microsoft has provided in
the .NET Framerwork you just installed. Unfortunately, you have to install
the examples (even though they're already on your computer).
1. Click on
"Start" -> "Programs" -> "Microsoft NGWS
SDK" -> "Sample Guide"
2. This will take you to a web page where
you must click on "Install NGWS SDK Samples". Extract the zipped
files.
5) Click on "Start" -> "Programs" -> "Microsoft NGWS SDK" -> "Reference Documentation" and look at this documentation.
6) Download the C# Manual and take a look at it.
The C# Language |
Type |
Description |
Examples |
object |
The ultimate base type of all other types |
object o = new
Stack(); |
string |
String type; a string is a sequence of Unicode characters |
string s =
"Hello"; |
sbyte |
8-bit signed integral type |
sbyte val = 12; |
short |
16-bit signed integral type |
short val = 12; |
int |
32-bit signed integral type |
int val = 12; |
long |
64-bit signed integral type |
long val1 = 12; |
byte |
8-bit unsigned integral type |
byte val1 = 12; |
ushort |
16-bit unsigned integral type |
ushort val1 = 12; |
uint |
32-bit unsigned integral type |
uint val1 = 12; |
ulong |
64-bit unsigned integral type |
ulong val1 = 12; |
float |
Single-precision floating point type |
float value =
1.23F; |
double |
Double-precision floating point type |
double val1 =
1.23 |
bool |
Boolean type; a bool value is either true or false |
bool value =
true; |
char |
Character type; a char value is a Unicode character |
char value = 'h'; |
decimal |
Precise decimal type with 28 significant digits |
decimal value =
1.23M; |
Operators and Keywords
operator-or-punctuator
{
} [
] (
) .
, :
;
+ -
* /
% &
| ^
! ~
= <
> ?
++ --
&& ||
<< >>
== !=
<= >=
+= -=
*= /=
%= &=
|= ^=
<<= >>=
->
= += -= *= /= %= &= |= ^= <<= >>=
keywords
abstract
base
bool
break byte
case catch
char
checked class
const continue
decimal
default delegate
do
double
else
enum
event
explicit extern
false finally
fixed
float for
foreach goto
if
implicit in
int
interface internal
is
lock
long
namespace new
null object
operator out
override
params private
protected public
readonly
ref
return sbyte
sealed
short
sizeof static
string struct
switch
this throw
true
try
typeof
uint ulong
unchecked
unsafe ushort
using virtual
void
while
Escape sequence |
Character name |
Unicode encoding |
\' |
Single quote |
0x0027 |
\" |
Double quote |
0x0022 |
\\ |
Backslash |
0x005C |
\0 |
Null |
0x0000 |
\a |
Alert |
0x0007 |
\b |
Backspace |
0x0008 |
\f |
Form feed |
0x000C |
\n |
New line |
0x000A |
\r |
Carriage return |
0x000D |
\t |
Horizontal tab |
0x0009 |
\v |
Vertical tab |
0x000B |
Arrays in C# may be single-dimensional or multi-dimensional. Both “rectangular” and “jagged” arrays are supported.
Single-dimensional arrays are the most common type, so this is a good starting point. The example
using System;
class Test
{
static void
Main() {
int[] arr = new int[5];
for (int i = 0; i < arr.Length; i++)
arr[i] = i * i;
for (int i = 0; i < arr.Length; i++)
Console.WriteLine("arr[{0}] = {1}", i, arr[i]);
}
}
An if statement selects a statement for execution based on the value of a boolean expression. An if statement may optionally include an else clause that executes if the boolean expression is false.
The example
using System;
class Test
{
static void
Main(string[] args) {
if (args.Length == 0)
Console.WriteLine("No arguments were provided");
else
Console.WriteLine("Arguments were provided");
}
}
shows a program that uses an if statement to write out two different messages depending on whether command-line arguments were provided or not.
A switch statement executes the statements that are associated with the value of a given expression, or a default of statements if no match exists.
The example
using System;
class Test
{
static void
Main(string[] args) {
switch (args.Length) {
case 0:
Console.WriteLine("No arguments were provided");
break;
case 1:
Console.WriteLine("One arguments was provided");
break;
default:
Console.WriteLine("{0} arguments were provided");
break;
}
}
}
switches on the number of arguments provided.
A while statement conditionally executes a statement zero or more times – as long as a boolean test is true.
using System;
class Test
{
static int
Find(int value, int[] arr) {
int i = 0;
while (arr[i] != value) {
if (++i > arr.Length)
throw new ArgumentException();
}
return i;
}
static
void Main() {
Console.WriteLine(Find(3, new int[] {5, 4, 3, 2, 1}));
}
}
uses a while statement to find the first occurrence of a value in an array.
The do statement
A do statement conditionally executes a statement one or more times.
The example
using System;
class Test
{
static void
Main() {
string s;
do {
s = Console.ReadLine();
}
while (s != "Exit");
}
}
reads from the console until the user types “Exit” and presses the enter key.
A for statement evaluates a sequence of initialization expressions and then, while a condition is true, repeatedly executes a statement and evaluates a sequence of iteration expressions.
The example
using System;
class Test
{
static void
Main() {
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
}
}
uses a for statement to write out the integer values 1 through 10.
A foreach statement enumerates the elements of a collection, executing a statement for each element of the collection.
The example
using System;
using System.Collections;
class Test
{
static void
WriteList(ArrayList list) {
foreach (object o in list)
Console.WriteLine(o);
}
static
void Main() {
ArrayList list = new ArrayList();
for (int i = 0; i < 10; i++)
list.Add(i);
Class
Class declarations are used to define new reference types. C# supports single inheritance only, but a class may implement multiple interfaces.
Class members can include constants, fields, methods, properties, indexers, events, operators, constructors, destructors, and nested type declaration.
Each member of a class has a form of accessibility. There are five forms of accessibility:
class Point
{
public int
x, y;
public
Point() {
x = 0;
y = 0;
}
public
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Test
{
static void
Main() {
Point[] points = new Point[100];
for (int i = 0; i < 100; i++)
points[i] = new Point(i, i*i);
}
}
Struct
The list of similarities between classes and structs is long – structs can implement interfaces, and can have the same kinds of members as classes. Structs differ from classes in several important ways, however: structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored either “on the stack” or “in-line”. Careful programmers can enhance performance through judicious use of structs.
For example, the use of a struct rather than a class for a Point can make a large difference in the number of allocations. The program below creates and initializes an array of 100 points. With Point implemented as a class, the program instantiates 101 separate objects – one for the array and one each for the 100 elements.
If Point is instead implemented as a struct, as in
struct Point
{
public int
x, y;
public
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
then the test program instantiates just one object, for the array. The Point instances are allocated in-line within the array. Of course, this optimization can be mis-used. Using structs instead of classes can also make your programs fatter and slower, as the overhead of passing a struct instance by value is slower than passing an object instance by reference. There is no substitute for careful data structure and algorithm design.
C# programs are organized using namespaces. Namespaces are used both as an “internal” organization system for a program, and as an “external” organization system – a way of presenting program elements that are exposed to other programs.
Earlier, we presented a “Hello, world” program. We’ll now rewrite this program in two pieces: a HelloMessage component that provides messages and a console application that displays messages.
First, we’ll provide a HelloMessage class in a namespace. What should we call this namespace? By convention, developers put all of their classes in a namespace that represents their company or organization. We’ll put our class in a namespace named Microsoft.CSharp.Introduction.
namespace Microsoft.CSharp.Introduction
{
public class
HelloMessage
{
public string GetMessage() {
return "Hello, world";
}
}
}
Namespaces are hierarchical, and the name Microsoft.CSharp.Introduction is actually shorthand for defining a namespace named Microsoft that contains a namespace named CSharp that itself contains a namespace named Introduction, as in:
namespace Microsoft
{
namespace
CSharp
{
namespace Introduction
{....}
}
}
Next, we’ll write a console application that uses the HelloMessage class. We could just use the fully qualified name for the class – Microsoft.CSharp.Introduction.HelloMessage – but this name is quite long and unwieldy. An easier way is to use a “using” directive, which makes it possible to use all of the types in a namespace without qualification.
using Microsoft.CSharp.Introduction;
class Hello
{
static void
Main() {
HelloMessage m = new HelloMessage();
System.Console.WriteLine(m.GetMessage());
}
}
Note that the two occurrences of HelloMessage are shorthand for Microsoft.CSharp.Introduction.HelloMessage.
C# also enables the definition and use of aliases. Such aliases can be useful in situation in which name collisions occur between two libraries, or when a small number of types from a much larger namespace are being used. Our example can be rewritten using aliases as:
using MessageSource = Microsoft.CSharp.Introduction.HelloMessage;
class Hello
{
static void
Main() {
MessageSource m = new MessageSource();
System.Console.WriteLine(m.GetMessage());
}
}
Names can be defined and undefined for use in pre-processing. A #define defines an identifier. A #undef "undefines" an identifier – if the identifier was defined earlier then it becomes undefined. If an identifier is defined then it is semantically equivalent to true; if an identifier is undefined then it is semantically equivalent to false.
pp-declaration:
#define
pp-identifier
#undef
pp-identifier
The example:
#define A
#undef B
class C
{
#if A
void F() {}
#else
void G() {}
#endif
#if B
void H() {}
#else
void I() {}
#endif
}
becomes:
class C
{
void F() {}
void I() {}
}
Within a pp-unit, declarations must precede pp-token elements. In other words, #define and #undef must precede any "real code" in the file, or a compile-time error occurs. Thus, it is possible to intersperse #if and #define as in the example below:
#define A
#if A
#define B
#endif
namespace N
{
#if B
class Class1
{}
#endif
}
The following example is illegal because a #define follows real code:
#define A
namespace N
{
#define B
#if B
class Class1
{}
#endif
}
A #undef may "undefine" a name that is not defined. The example below defines a name and then undefines it twice; the second #undef has no effect but is still legal.
#define A
#undef A
#undef A
The throw statement throws an exception.
throw-statement:
throw
expressionopt ;
A throw statement with an expression throws the exception produced by evaluating the expression. The expression must denote a value of the class type System.Exception or of a class type that derives from System.Exception. If evaluation of the expression produces null, a NullReferenceException is thrown instead.
A throw statement with no expression can be used only in a catch block. It re-throws the exception that is currently being handled by the catch block.
The try statement provides a mechanism for catching exceptions that occur during execution of a block. The try statement furthermore provides the ability to specify a block of code that is always executed when control leaves the try statement.
try-statement:
try
block catch-clauses
try
block finally-clause
try
block catch-clauses
finally-clause
catch-clauses:
specific-catch-clauses general-catch-clauseopt
specific-catch-clausesopt
general-catch-clause
specific-catch-clauses:
specific-catch-clause
specific-catch-clauses specific-catch-clause
specific-catch-clause:
catch
(
class-type identifieropt
)
block
general-catch-clause:
catch
block
finally-clause:
finally
block
There are three possible forms of try statements:
· A try block followed by one or more catch blocks.
· A try block followed by a finally block.
A try block followed by one or more catch blocks followed by a finally blockConclusion
C-sharp is a new language from Microsoft, and it is a part of their .NET project. Microsoft promises the flexibility of Java and performance of C and C++ in C-sharp while with .NET project they are opening C#, VB and many other mainly windows based languages to other platforms. .NET project has lot of new ideas and if Microsoft can deliver what they told us about C# and the .NET project then C# could be the next big programming language.
Microsoft
References |
What
is .NET? |
.NET
is Microsoft's strategy for developing and delivering next generation software
products and web services.
In .NET, Microsoft's focus is web based application than the
desktop.
Three key elements of
.NET are:
·
Microsoft
.NET platform
Includes .NET infrastructure and tools to build and operate a new generation of
services, .NET user experience to enable rich clients, .NET building block
services and .NET device software to enable a new generation of smart Internet
devices.
·
Microsoft
.NET products and services
Includes Microsoft® Windows.NET (with a core integrated set of building block
services), MSN.NET, personal subscription services, Microsoft® Office.NET,
Microsoft® Visual Studio.NET, and Microsoft® bCentral™ for .NET.
·
Third-party
.NET services
A vast range of partners and developers will have the opportunity to produce
corporate and vertical services built on the .NET platform
Extra
link space... if we need to link something |
Microsoft
References |
Books |
C# Tutorials |