|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionC# is a language with the features of C++, programming style like Java and rapid application model of BASIC. If you already know the C++ language, it will take you less than an hour to quickly go through the syntax of C#. Familiarity with Java will be a plus, as Java program structure, the concept of packages and garbage collection will definitely help you learn C# more quickly. So while discussing C# language constructs, I will assume, you know C++. This article discusses the C# language constructs and features using code examples, in a brief and comprehensive way, so that you just by having a glance at the code, can understand the concepts. Note: This article is not for C# gurus. There must be some other beginner's articles on C#, but this is yet another one. Following topics of C# language are discussed:
Following are not discussed:
Program structureLike C++, C# is case-sensitive. Semi colon ( Have a look at this Hello world program in C#. using System;
namespace MyNameSpace
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine ("Hello World");
}
}
}
Everything in C# is packed into a class and classes in C# are packed into namespaces (just like files in a folder). Like C++, a main method is the entry point of your program. C++'s main function is called No need to put a semi colon after a class block or NamespaceEvery class is packaged into a namespace. Namespaces are exactly the same concept as in C++, but in C# we use namespaces more frequently than in C++. You can access a class in a namespace using dot ( Now consider you want to access the using System;
namespace AnotherNameSpace
{
class AnotherClass
{
public void Func()
{
Console.WriteLine ("Hello World");
}
}
}
Now from your using System;
using AnotherNameSpace; // you will add this using statement
namespace MyNameSpace
{
class HelloWorld
{
static void Main(string[] args)
{
AnotherClass obj = new AnotherClass();
obj.Func();
}
}
}
In .NET library, You can also define nested namespaces. UsingThe VariablesVariables in C# are almost the same as in C++ except for these differences:
Data typesAll types of C# are derived from a base class
Following is a table which lists built-in C# types:
Note: Type range in C# and C++ are different, example, long in C++ is 4 bytes, and in C# it is 8 bytes. Also the User defined types includes:
Memory allocation of the data types divides them into two types:
Value typesValues types are those data types which are allocated in stack. They include:
Reference typesReference types are allocated on heap and are garbage collected when they are no longer being used. They are created using Reference types include:
EnumerationEnumerations in C# are exactly like C++. Defined through a keyword Example: enum Weekdays
{
Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
}
Classes and structs
Examples: struct Date
{
int day;
int month;
int year;
}
class Date
{
int day;
int month;
int year;
string weekday;
string monthName;
public int GetDay()
{
return day;
}
public int GetMonth()
{
return month;
}
public int GetYear()
{
return year;
}
public void SetDay(int Day)
{
day = Day ;
}
public void SetMonth(int Month)
{
month = Month;
}
public void SetYear(int Year)
{
year = Year;
}
public bool IsLeapYear()
{
return (year/4 == 0);
}
public void SetDate (int day, int month, int year)
{
}
...
}
PropertiesIf you are familiar with the object oriented way of C++, you must have an idea of properties. Properties in above example of So above class can be written as: using System;
class Date
{
public int Day{
get {
return day;
}
set {
day = value;
}
}
int day;
public int Month{
get {
return month;
}
set {
month = value;
}
}
int month;
public int Year{
get {
return year;
}
set {
year = value;
}
}
int year;
public bool IsLeapYear(int year)
{
return year%4== 0 ? true: false;
}
public void SetDate (int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
}
Here is the way you will get and set these properties:
class User
{
public static void Main()
{
Date date = new Date();
date.Day = 27;
date.Month = 6;
date.Year = 2003;
Console.WriteLine
("Date: {0}/{1}/{2}", date.Day, date.Month, date.Year);
}
}
ModifiersYou must be aware of readonly
class MyClass
{
const int constInt = 100; //directly
readonly int myInt = 5; //directly
readonly int myInt2;
public MyClass()
{
myInt2 = 8; //Indirectly
}
public Func()
{
myInt = 7; //Illegal
Console.WriteLine(myInt2.ToString());
}
}
sealed
sealed class CanNotbeTheParent
{
int a = 5;
}
unsafeYou can define an unsafe context in C# using public unsafe MyFunction( int * pInt, double* pDouble)
{
int* pAnotherInt = new int;
*pAnotherInt = 10;
pInt = pAnotherInt;
...
*pDouble = 8.9;
}
InterfacesIf you have an idea of COM, you will immediately know what I am talking about. An using System;
interface myDrawing
{
int originx
{
get;
set;
}
int originy
{
get;
set;
}
void Draw(object shape);
}
class Shape: myDrawing
{
int OriX;
int OriY;
public int originx
{
get{
return OriX;
}
set{
OriX = value;
}
}
public int originy
{
get{
return OriY;
}
set{
OriY = value;
}
}
public void Draw(object shape)
{
... // do something
}
// class's own method
public void MoveShape(int newX, int newY)
{
.....
}
}
ArraysArrays in C# are much better than C++. Arrays are allocated in heap and thus are reference types. You can't access an out of bound element in an array. So C# prevents you from that type of bugs. Also some helper functions to iterate array elements are provided.
C# supports single dimensional, multi dimensional, and jagged arrays (array of array). Examples: int[] array = new int[10]; // single-dimensional array of int
for (int i = 0; i < array.Length; i++)
array[i] = i;
int[,] array2 = new int[5,10]; // 2-dimensional array of int
array2[1,2] = 5;
int[,,] array3 = new int[5,10,5]; // 3-dimensional array of int
array3[0,2,4] = 9;
int[][] arrayOfarray = new int[2]; // Jagged array - array of array of int
arrayOfarray[0] = new int[4];
arrayOfarray[0] = new int[] {1,2,15};
IndexersIndexer is used to write a method to access an element from a collection, by straight way of using Example: Note: class Shapes: CollectionBase
{
public void add(Shape shp)
{
List.Add(shp);
}
//indexer
public Shape this[int index]
{
get {
return (Shape) List[index];
}
set {
List[index] = value ;
}
}
}
Boxing/UnboxingThe idea of boxing is new in C#. As mentioned above, all data types, built-in or user defined, are derived from a base class Example: class Test
{
static void Main()
{
int myInt = 12;
object obj = myInt ; // boxing
int myInt2 = (int) obj; // unboxing
}
}
Example shows both boxing and unboxing. An Function parametersParameters in C# are of three types:
If you have an idea of COM interface and it's parameters types, you will easily understand the C# parameter types. By-Value/In parametersThe concept of value parameters is same as in C++. The value of the passed value is copied into a location and is passed to the function. Example: SetDay(5);
...
void SetDay(int day)
{
....
}
By-Reference/In-Out parametersThe reference parameters in C++ are passed either through pointers or reference operator You can not pass an un-initialized reference parameter into a function. C# uses a keyword Example: int a= 5;
FunctionA(ref a); // use ref with argument or you will get compiler error
Console.WriteLine(a); // prints 20
void FunctionA(ref int Val)
{
int x= Val;
Val = x* 4;
}
Out parameterOut parameter is the parameter which only returns value from the function. The input value is not required. C# uses a keyword Example: int Val;
GetNodeValue(Val); bool GetNodeValue(out int Val)
{
Val = value;
return true;
}
Variable number of parameters and arraysArrays in C# are passed through a keyword Note: This is the only way C# provides for optional or variable number of parameters, that is using array. Example: void Func(params int[] array)
{
Console.WriteLine("number of elements {0}", array.Length);
} Func(); // prints 0
Func(5); // prints 1
Func(7,9); // prints 2
Func(new int[] {3,8,10}); // prints 3
int[] array = new int[8] {1,3,4,5,5,6,7,5};
Func(array); // prints 8
Operators and expressionsOperators are exactly the same as of C++ and thus the expression also. However some new and useful operators are also added. Some of them are discussed here. is operator
void function(object param)
{
if(param is ClassA)
//do something
else if(param is MyStruct)
//do something
}
}
as operator
Shape shp = new Shape();
Vehicle veh = shp as Vehicle; // result is null, types are not convertable
Circle cir = new Circle();
Shape shp = cir;
Circle cir2 = shp as Circle; //will be converted
object[] objects = new object[2];
objects[0] = "Aisha";
object[1] = new Shape();
string str;
for(int i=0; i&< objects.Length; i++)
{
str = objects[i] as string;
if(str == null)
Console.WriteLine("can not be converted");
else
Console.WriteLine("{0}",str);
}
Output:
Aisha
can not be converted
StatementsStatements in C# are just like in C++ except some additions of new statements and modifications in some statements. Followings are new statements: foreachFor iteration of collections like arrays etc. Example: foreach (string s in array)
Console.WriteLine(s);
lockUsed in threads for locking a block of code making it a critical section. checked/uncheckedThe statements are for overflow checking in numeric operations. Example: int x = Int32.MaxValue; x++; // Overflow checked
{
x++; // Exception
}
unchecked
{
x++; // Overflow}
}
Following statements are modified:
Switch
DelegatesDelegates let us store function references into a variable. In C++, this is like using and storing function pointer for which we usually use Delegates are declared using a keyword Example: delegate int Operation(int val1, int val2);
public int Add(int val1, int val2)
{
return val1 + val2;
}
public int Subtract (int val1, int val2)
{
return val1- val2;
}
public void Perform()
{
Operation Oper;
Console.WriteLine("Enter + or - ");
string optor = Console.ReadLine();
Console.WriteLine("Enter 2 operands");
string opnd1 = Console.ReadLine();
string opnd2 = Console.ReadLine();
int val1 = Convert.ToInt32 (opnd1);
int val2 = Convert.ToInt32 (opnd2);
if (optor == "+")
Oper = new Operation(Add);
else
Oper = new Operation(Subtract);
Console.WriteLine(" Result = {0}", Oper(val1, val2));
}
Inheritance and polymorphismOnly single inheritance is allowed in C#. Multiple inheritance can be achieved using interfaces. Example: class Parent{
}
class Child : Parent
Virtual functionsVirtual functions to implement the concept of polymorphism are same in C#, except you use the class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}
class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
class Square : Rectangle
{
public override void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();
shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
}
}
Output:
Shape.Draw
Rectangle.Draw
Square.Draw
Hiding parent functions using "new"You can define in a child class a new version of a function, hiding the one which is in base class. A keyword class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}
class Rectangle : Shape
{
public new void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
class Square : Rectangle
{
//wouldn't let u override it here
public new void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Using Polymorphism:");
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();
shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
Console.WriteLine("Using without Polymorphism:");
rect.Draw();
Square sqr = new Square();
sqr.Draw();
}
}
Output:
Using Polymorphism
Shape.Draw
Shape.Draw
Shape.Draw
Using without Polymorphism:
Rectangle.Draw
Square.Draw
See how the polymorphism doesn't take the Note: you can not use in the same class the two versions of a method, one with Calling base class membersIf the child class has the data members with same name as that of base class, in order to avoid naming conflicts, base class data members and functions are accessed using a keyword public Child(int val) :base(val)
{
myVar = 5;
base.myVar;
}
OR
public Child(int val)
{
base(val);
myVar = 5 ;
base.myVar;
}
Future additionsThis article is just a quick overview of the C# language so that you can just become familiar with the language features. Although I have tried to discuss almost all the major concepts in C# in a brief and comprehensive way with code examples, yet I think there is lot much to be added and discussed. In future, I would like to add more commands and concepts not yet discussed, including events etc. I would also like to write for beginners, about Windows programming using C#. References:
Modifications:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||