Introduction
C# 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:
Program structure
Namespaces
Data types
Variables
Operators and expressions
Enumerations
Statements
Classes and structs
Modifiers
Properties
Interfaces
Function parameters
Arrays
Indexers
Boxing and unboxing
Delegates
Inheritance and polymorphism
Following are not discussed:
Things which are common in C++ and C#.
Concepts like garbage collection, threading, file processing etc.
Data type conversions
Exception handling
.NET library
Program structure
Like C++, C# is case-sensitive. Semi colon ( is the statement separator. Unlike C++, there are no separate declaration (header) and implementation (CPP) files in C#. All code (class declaration and implementation) is placed in one file with extension cs.
Have a look at this Hello world program in C#.
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 main whereas C#'s main function starts with capital M and is named as Main.using System;
namespace MyNameSpace
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine ("Hello World");
}
}
}
No need to put a semi colon after a class block or struct definition. It was in C++, C# doesn't require that.
Namespace
Every 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 (.) qualifier. MyNameSpace is the namespace in hello world program above.
Now consider you want to access the HelloWorld class from some other class in some other namespace.
Now from your HelloWorld class you can access it as:using System;
namespace AnotherNameSpace
{
class AnotherClass
{
public void Func()
{
Console.WriteLine ("Hello World");
}
}
}
In .NET library, System is the top level namespace in which other namespaces exist. By default there exists a global namespace, so a class defined outside a namespace goes directly into this global namespace and hence you can access this class without any qualifier.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();
}
}
}
You can also define nested namespaces.
Using
The #include directive is replaced with using keyword, which is followed by a namespace name. Just as using System as above. System is the base level namespace in which all other namespaces and classes are packed. The base class for all objects is Object in the System namespace.
Variables
Variables in C# are almost the same as in C++ except for these differences:
1. Variables in C# (unlike C++), always need to be initialized before you access them, otherwise you will get compile time error. Hence, it's impossible to access an un-initialized variable.
2. You can't access a “dangling” pointer in C#.
3. An expression that indexes an array beyond its bounds is also not accessible.
4. There are no global variables or functions in C# and the behavior of globals is achieved through static functions and static variables.
Data types
All types of C# are derived from a base class object. There are two types of data types:
1. Basic/ built-in types
2. User-defined types
Following is a table which lists built-in C# types:
Type --- Bytes --- Description
byte --- 1 --- unsigned byte
sbyte --- 1 --- signed byte
short --- 2 --- signed short
ushort --- 2 --- unsigned short
int --- 4 --- signed integer
uint --- 4 --- unsigned integer
long --- 8 --- signed long
ulong --- 8 --- unsigned long
float --- 4 --- floating point number
double --- 8 --- double precision number
decimal --- 8 --- fixed precision number
string --- Unicode string
char --- Unicode char
bool --- true, false--- boolean
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 bool and string types are different than those in C++. bool accepts only true and false and not any integer.
User defined types includes:
1. Classes
2. Structs
3. Interfaces
Memory allocation of the data types divides them into two types:
1. Value types
2. Reference types
Value types
Values types are those data types which are allocated in stack. They include:
All basic or built-in types except strings
Structs
Enum types
Reference types
Reference types are allocated on heap and are garbage collected when they are no longer being used. They are created using new operator, and there is no delete operator for these types unlike C++ where user has to explicitly delete the types created using delete operator. In C#, they are automatically collected by garbage collector.
Reference types include:
Classes
Interfaces
Collection types like Arrays
String
Enumeration
Enumerations in C# are exactly like C++. Defined through a keyword enum.
Example:
Classes and structsenum Weekdays
{
Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
}
Classes and structs are same as in C++, except the difference of their memory allocation. Objects of classes are allocated in heap, and are created using new, where as structs are allocated in stack. Structs in C# are very light and fast data types. For heavy data types, you should create classes.
Examples:
Propertiesstruct 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)
{
}
...
}
If you are familiar with the object oriented way of C++, you must have an idea of properties. Properties in above example of Date class are day, month and year for which in C++, you write Get and Set methods. C# provides a more convenient, simple and straight forward way of accessing properties.
So above class can be written as:
Modifiersusing 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);
}
}
You must be aware of public, private and protected modifiers that are commonly used in C++. I will here discuss some new modifiers introduced by C#.
readonly
readonly modifier is used only for the class data members. As the name indicates, the readonly data members can only be read, once they are written either by directly initializing them or assigning values to them in constructor. The difference between the readonly and const data members is that const requires you to initialize with the declaration, that is directly. See example code:
sealedclass 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 modifier with a class don't let you derive any class from it. So you use this sealed keyword for the classes which you don't want to be inherited from.
unsafesealed class CanNotbeTheParent
{
int a = 5;
}
You can define an unsafe context in C# using unsafe modifier. In unsafe context, you can write an unsafe code, example: C++ pointers etc. See the following code:
Interfacespublic unsafe MyFunction( int * pInt, double* pDouble)
{
int* pAnotherInt = new int;
*pAnotherInt = 10;
pInt = pAnotherInt;
...
*pDouble = 8.9;
}
If you have an idea of COM, you will immediately know what I am talking about. An interface is the abstract base class containing only the function signatures whose implementation is provided by the child class. In C#, you define such classes as interfaces using the interface keyword. .NET is based on such interfaces. In C#, where you can't use multiple class inheritance, which was previously allowed in C++, the essence of multiple inheritance is achieved through interfaces. That's your child class may implement multiple interfaces.
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)
{
.....
}
}
Bookmarks