C Sharp
C# Language Basics
What is C# all about?
C# was developed at Microsoft. It is an object-oriented programming language and provides excellent features such as strong type checking, array bounds checking and automatic garbage collection. We will explore these and several other features in this article.
C# has features that make it an excellent choice for developing robust distributed n-tier Enterprise applications, web applications, windows applications and embedded systems. It is used for building applications ranging from the very large that use sophisticated operating systems, down to the very small having specialist functions
Getting Started:
Here is a very simple “Hello World” program written using C#. The code for C# program is written in text files with an extension “.cs”
Example:
1) Create a text file “First.cs”
2) Type the following code and ‘save’
using System;
class myClass
{
static void Main()
{
Console.WriteLine("Hello World");
}
}
3) From the command line compile the above code by typing the following
csc First.cs
4) This creates First.exe
5) Run this exe from the command line and you see an output –
Hello World
Having seen the example above we will now review the concepts and elements of the C# programming language. After that we will review the above example once again to understand what each line of code does. To get a better grasp of the C# language it is helpful if you have some programming experience and even better if you have experience in Object Oriented Programming. We now examine the C# language concepts and elements one by one.
A) OOP
C# is an object oriented Programming language and it supports the Object Oriented Programming Methodology. When creating a software solution you can represent the real world entities as “objects” of different “types”.
a. Types: C# supports mainly two kinds of types: value types and Reference types. The difference lies in the way in which handles these tow kinds of types. Examples of value types are – char, int, structures, enums . Examples of Reference types are – class, interface, delegate, arrays
i. Variables represent storage locations. Every variable is of a specific ‘type’. This determines what values can be stored in it.
ii. Field is a variable that is associated with a Class or Struct, or an instance of a class or struct.
iii. Parameters: There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.
iv. Classes: Classes are blueprints for objects. You instantiate an object from class. An object thus instantiated if said to be of a reference types. As C# is an Object Oriented Programming Language a class can inherit from another class, and can implement interfaces. Each Class can have one or members such as methods, properties, constants, fields, events, constructors, destructors and so on.
v. Structs: Structs are similar to classes in many ways. They have members and they can implement interfaces. They are fundamentally different from classes. STRUCTS are value types. STRUCT values are stored "on the stack" or "in-line". They cannot be inherited from any other class or reference type.
vi. Interfaces: What is an interface? An Interface simplifies a complex process by providing easy to use methods. Consider you need to change the channel on your TV or increase its volume, how do we do this, we use a Remote Control to change the channel or increase the volume. In this context, a Remote Control acts as an interface between you and your TV. Using a Remote Control one can perform required operation and control various functionality available in TV.
An interface defines a contract. When a class or a struct implements an interface with the help of methods and properties. A type (CLASS or STRUCT) that implements an interface must adhere to its contract. Interfaces can contain methods, properties, events, and indexers as members.
vii. Delegates: C# implements the functionality of function pointers using Delegates.
A delegate instance encapsulates a list of one or more methods, each of which is referred to as a callable entity. When a delegate instance is invoked it causes the delegate instance's callable entity to be invoked.
viii. Enums: An enum type declaration defines a type name for a related group of symbolic constants.
ix. Predefined types: The predefined value types include
§ signed integral types (sbyte, short, int, and long)
§ unsigned integral types (byte, ushort, uint, and ulong)
§ floating-point types (float and double)
§ bool
§ char
§ decimal
x. Nullable types These are constructed using the ‘?’ type modifier.
int? is the nullable form of the predefined type int.
int? x = 42;
int? z = null;
The nullable type is a structure. This structure has two members :
- A value of the underlying type (“Value”)
- A Boolean null indicator (“HasValue”)
HasValue is true for a non-null instance and false for a null instance. When HasValue is true, the Value property returns the contained value.
When HasValue is false, an attempt to access the Value property throws an exception.
if (x.HasValue) Console.WriteLine(x.Value);
An implicit conversion exists from any non-nullable value type to a nullable form of that type.
B) Namespaces
C# programs are organized using namespaces. Namespaces provide a hierarchical means of organizing the elements of one or more programs. They also provide a way of presenting program elements that are exposed to other programs. For instance in our example
using System;
class myClass
{
static void Main()
{
Console.WriteLine("Hello World");
}
}
The statement – “using system;” helps us use the “Console” class in it. A namespace-declaration consists of the keyword namespace, followed by a namespace name and body
namespace Company1.Dept2
{
class manager {}
class emp {}
}
namespace Company1
{
namespace Dept2
{
class manager {}
class emp {}
}
}
Namespaces are open-ended, and two namespace declarations with the same fully qualified name contribute to the same declaration space In the example
namespace Company1.Dept2
{
class manager {}
}
namespace Company1.Dept2
{
class emp {}
}
the two namespace declarations above contribute to the same declaration space,
Assemblies Assemblies are used for physical packaging and deployment. An assembly can contain the executable code and references to other assemblies.
C) Language Grammar
a. Expressions: An expression is a sequence of operands (variables, literals, etc) and operators An expression can be classified as one of the following:
§ value
§ variable
§ namespace
§ type
§ method group
§ property access
§ event access
§ indexer access
§ void or Nothing
The output of an expression can never be a namespace, type, method group, or
b. Statements: C# statements can be classified as one of the following:
§ labeled-statement
§ declaration-statement
§ embedded-statement
§ embedded-statement: (statements that appear within other statements)
§ empty-statement
§ expression-statement
§ selection-statement
§ iteration-statement
§ jump-statement
§ try-statement
§ checked-statement
§ unchecked-statement
§ lock-statement
§ using-statement
c. Constants: A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants can depend on other constants within the same program.
class myClass
{
public const int A = 1;
public const int B = A + 1;
}
d. Fields: A field is a member that represents a variable associated with an object or class.
e. Operators: The operators of an expression indicate which operations to apply to the operands. Examples of operators: +, -, *, /, new. There are three kinds of operators:
§ Unary operators. The unary operators take one operand and use either prefix notation (such as –-counter) or postfix notation (such as counter++).
§ Binary operators. The binary operators take two operands and all use infix notation (such as intA + intY).
§ Ternary operator. Only one ternary operator, ?:, exists; it takes three operands and uses infix notation (condition? intX: intY).
Certain operators can be overloaded. Operator overloading permits user-defined behavior for the operator.
f) Methods: A method is a member of the class. It implements functionality or behavior or action that can be performed by an instance of that class. Methods can have one or more formal parameters, an optional return value
g) Properties: A property is a member of the class. It provides access to a feature or characteristic of an instance of the class. In the example below: class car has a property CarColor
public class car
{
private string _CarColor;
public string CarColor
{
get
{
return _CarColor;
}
set
{
_CarColor = value;
}
}
}
h) Event: An event is also a member of the class. It enables an object or class to provide notifications when an event occurs. Example
public delegate void EventHandler(object sender, System.EventArgs e);
public class Button
{
public event EventHandler Click;
public void Reset() {
Click = null;
}
}
using System;
public class Form1
{
public Form1() {
Button1.Click += new EventHandler(doSomething);
}
Button Button1 = new Button();
void doSomething(object sender, EventArgs e) {
Console.WriteLine("Button1 was clicked and I did Something!");
}
public void Disconnect() {
Button1.Click -= new EventHandler(doSomething);
}
}
i) Comments: Two forms of comments are supported: delimited comments and single-line comments. A delimited comment begins with the characters /* and ends with the characters */. Delimited comments can occupy a portion of a line, a single line, or multiple lines. A single-line comment begins with the characters // and extends to the end of the line.
/* This is my First Program
This is where it gets started
*/
class myFirstProgram
{
static void Main() {
System.Console.WriteLine("Welcome Aboard!"); // Comment
}
}
j) Conditional Statements The if statement selects a statement for execution based on the value of a Boolean expression. Examples:
if ( boolean-expression ) embedded-statement
if ( boolean-expression ) embedded-statement else embedded-statement
if (x) if (y) F(); else G();
if (x)
{
if (y) {
F();
}
else {
G();
}
}
The switch statement: Based on the value of the switch expression. The switch statement matches a switch label and executes the statement(s) that corresponds to it
Example:
switch (iMatch) {
case 0:
Matched_Zero();
break;
case 1:
Matched_One();
break;
default:
Matched_None();
break;
}
k) Iteration statements : Iteration statements repeatedly execute an embedded statement.
Types of iteration statements:
§ while-statement
§ do-statement
§ for-statement
§ foreach-statement
Keywords in C#
abstract | as | 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 | stackalloc | static | string |
struct | switch | this | throw | true |
try | typeof | uint | ulong | unchecked |
unsafe | ushort | using | virtual | void |
volatil | while | | | |
l) Conversions A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit. A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.
A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.
m) Arrays An array is a data structure. It contains one or more variables that are accessed through computed indices. The elements of the array, are all of the same type.
n) Memory Management: One of the most important features of C# is automatic memory management implemented using a ‘garbage collector’. The process scans thru the objects created in the program and if the object can no longer be accessed the memory is cleared up
o) Indexers : An indexer enables an object to be indexed in the same way as an array.
Indexer declarations are similar to property declarations. The indexing parameters are provided between square brackets. Example
using System;
public class AllmyCars
{
private Car GetCar(int index)
{
//process and return appropriate car
}
public object this[int index]
{
get
{
return GetCar (index).Value;
}
set
{
GetCar(index).Value = value;
}
}
}
class Test
{
static void Main()
{
AllmyCars c = new AllmyCars();
c[0] = “Rolls Royce”;
c[1] = “Alpha Romeo”;
c[2] = “Saab”;
}
}
Inheritance in C#
Inheritance in C#
This article discusses Inheritance concepts in the context of C# Before we understand Inheritance in C# it is important to understand the key players involved, viz Objects, Classes and Structs
Classes and Structs are ‘blue-prints’ or templates from which we instantiate (create) objects Example a car may be created based on its blue print Car is the object and blue print is the class (or template)
What are types?
An object can be of the following types – Class or Struct There are many differences between the two ‘types’ The main difference between the two is the way in which they are stored in memory and the way they are accessed Classes are also called reference types Structs are known as value types Classes are stored in a memory space called ‘heap’ and Structs are stored in a memory space known as ‘stack’
Constructors:
In C#, (like other Objected Oriented languages) constructor is a method having the same name as the class The constructor is called when the object is being created It can have one or more parameters
Interfaces:
In the context of C#, an interface provides a contract A class that is derived from this interface will implement the functions specified by the interface
Inheritance:
C# supports two types of Inheritance mechanisms
1)Implementation Inheritance
2) Interface Inheritance
What is Implementation Inheritance?
- When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance
What is Interface Inheritance?
- When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance
In general Classes can be derived from another class, hence support Implementation inheritance At the same time Classes can also be derived from one or more interfaces Hence they support Interface inheritance Structs can derive from one more interface, hence support Interface Inheritance Structs cannot be derived from another class they are always derived from SystemValueType
Multiple Inheritance:
C# does not support multiple implementation inheritance A class cannot be derived from more than one class However, a class can be derived from multiple interfaces
Inheritance Usage Example:
Here is a syntax example for using Implementation Inheritance
Class derivedClass:baseClass
{
}
derivedClass is derived from baseClass
Interface Inheritance example:
private Class derivedClass:baseClass , InterfaceX , InterfaceY
{
}
derivedClass is now derived from interfaces – InterfaceX, InterfaceY
Similarly a struct can be derived from any number of interfaces
private struct childStruct:InterfaceX, InterfaceY
{
}
Virtual Methods:
If a function or a property in the base class is declared as virtual it can be overridden in any derived classes
Usage Example:
class baseClass
{
public virtual int fnCount()
{
return 10;
}
}
class derivedClass :baseClass
{
public override int fnCount()
{
return 100;
}
}
This is useful because the compiler verifies that the ‘override’ function has the same signature as the virtual function
Hiding Methods:
Similar to the above scenario if the methods are declared in a child and base class with the same signature but without the key words virtual and override, the child class function is said to hide the base class function
class someBaseClass
{
}
class abcClass:someBaseClass
{
public int fnAge()
{
return 99;
}
}
class grandchildClass: abcClass
{
public int fnAge()
{
return 10;
}
}
In the example above the function fnAge in grandChildClass hides the function fnAge in its parent class ie abcClass
The C# compiler will generate a warning in this case The new keyword should be used when we intend to hide a method
Example:
class grandchildClass: abcClass
{
public new int fnAge()
{
return 10;
}
}
Calling Functions from the Base Class:
To call a function from the base class simply use the key word basefunctionname()
class basicMember
{
public virtual float membershipFee()
{
return 100;
}
}
class vipMember:basicMember
{
public override float membershipFee()
{
return 200;
}
public float promoMembershipFee()
{
return basemembershipFee() + 60;
}
}
What are Abstract Classes?
1) An abstract class cannot be instantiated
2) An abstract class can have one or more abstract functions
3) Abstract functions are virtual
4) They do not have any implementation
5) They need to be overridden and implemented in a derived non-abstract class
Abstract Classes and Functions example:
abstract class Car
{
public int headlights = 2;
public abstract price();
}
Sealed Classes:
If a class is declared as Sealed you cannot inherit from that class
Declaring a method as sealed prevents it from being overridden
sealed class LastManStanding
{
}
The compiler gives an error if any other class tries to derive from the above class
class bankManager
{
public sealed override bool authorize()
{
}
}
The compiler gives an error if you override the above method
Constructors and Inheritance:
C# allocates a default zero parameter constructor to every class that does not have any explicit constructors defined If you instantiate a child class, all the constructors in the hierarchy are called The base call constructor is called first and then the next child class constructor This sequence continues until all the constructors are called If an explicit constructor is defined for a class anywhere in the hierarchy there is a possibility that the above chain is broken If this is the case the compiler raises an Error and the code will not compile
For instance, if you declare an explicit constructor with one or more parameters the above described sequence of calls to constructors in the class hierarchy which was being handled automatically is now broken This is because when you supply a constructor C# does not provide a default constructor In this case, we have to explicitly maintain the ‘chain’ Another scenario for this error is when you define an explicit constructor with zero parameters and mark it as private The compiler will raise an error in this case
Visibility Modifiers in C#:
public: Any types or members can be prefixed with this modifer If a member or type is prefixed with public it is visible to all the code
protected: It can be used for any member or a nested type This causes the member/nested type to be visible to any derived type
private: This can be used for any type or member and the member/type will be visible only inside the type where it was defined
internal: This causes the member/nested type to be visible within the assembly where it is defined
protected or internal: This causes the member/nested type to be visible within the assembly where it is defined and any derived type
Interfaces:
When a class derives from an Interface it implements the functions specified by the interface
Defining an Interface
We can define an interface as follows:
public interface IbankManager
{
bool authorize();
}
Implementing an Interface
The above interface can be implemented as follows:
public class newManager:IbankManager
{
public bool authorize()
{
//process
return true;
}
}
Deriving an Interface
Interfaces can be derived from other interfaces
Example:
public interface IbranchManager:IbankManager
{
public string sendReports();
}
Delegates in C#
Delegates in C#
Most programmers are used to passing data in methods as input and output parameters.
Imagine a scenario where you wish to pass methods around to other methods instead of data. Amazed! Read further.
Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time.
In this case you need to pass the unknown method as a parameter. The method that you are passing in is known as a Callback function. Call back functions are pointers to methods.
.NET implements the concept of function pointers using delegates.
§ Delegate wraps a method. Calling delegate results in calling the method.
§ Delegate is a type of object very similar to classes.
§ Delegate gives a name to a method signature.
Where are Delegates used?
The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.
This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.
Starting Threads/Parallel Processing:
You defined several methods and you wish to execute them simultaneously and in parallel to whatever else the application is doing. This can be achieved by starting new threads. To start a new thread for your method you pass your method details to a delegate.
Generic Classes: Delegates are also used for generic class libraries which have generic functionality defined. However the generic class may need to call certain functions defined by the end user implementing the generic class. This can be done by passing the user defined functions to delegates.
Creating and Using Delegates:
Using delegates is a two step process-
..........1) Define the delegate to be used
..........2) Create one or more instances of the delegate
Syntax for defining a delegate:
delegate string reviewStatusofARegion();
to define a delegate we use a key word delegate followed by the method signature the delegate represents. In the above example string reviewStatusofARegion(); represents any method that returns a string and takes no parameters.
Syntax for creating an instance of the delegate:
reviewStatusofARegion = new reviewStatusofARegion(myClass.getEurope)
private string getEurope()
{
return “Doing Great in Europe”;
}
To create an instance of the delegate you call its constructor. The delegate constructor takes one parameter which is the method name.
The method signature should exactly match the original definition of the delegate. If it does not match the compiler would raise an Error.
Multicast Delegate:
Delegate wraps a method. Calling delegate results in calling the method. It is possible to wrap more than one method in a delegate. This is known as a multicast delegate.
If you make a call to a multicast delegate it will call all the functions it wraps in the order specified. Please note that functions in this case should not return any values.
Syntax for defining a delegate:
delegate void deleteRowsinTable( int Year)
Syntax for instantiating the delegate:
deleteRowsinTable Cleanup = new deleteRowsinTable(archiveCompletedTasks)
Cleanup += new deleteRowsinTable(purgeCompletedTasks)
Using Delegates in Event Handling
Events could be visualized as following:
Example: You setup a wakeup alarm in your clock for 6 a.m.
Hence you need a class/object that creates and fires an event
You need a mechanism to notify all
You need a method to listen for the notification
Finally, you need a method that does something when the notification is received.
Another example