Data Types
A Variable is a named cell of memory used for data storage. A
Variable value can be changed anytime. Every variable must have
a type and this type must be set before it is used. Qualifying a
variable with a type is called as declaration of variable. The type of
a variable is the most important aspect and it defines the behavior
of variable. All variables can be divided into seven main categories
depending on the context of usage:
1. Static variables
2. Variable of instance
3. Array's elements
4. Parameters given by reference
5. Parameters given by value
6. Returned values
7. Local variables.
sum1 = a+b;
Console.WriteLine("The sum1 of elements {0} and {1} is
{2}",a,b,a+b);
return sum1;
int sume ;
sume = SumeOut(2,2, out sume);
Constants in C#:
Value type stores real data. When the data are queried by different
function a local copy of it these memory cells are created. It
guarantees that changes made to our data in one function don't
change them in some other function. Let see at a simple example:
Here we have simple class that contains only one public data field
of integer type. Now have a look on its usage in main function:
In the above example, assume that First we have two value type
i and j. Also assume that the second variable is initialized with the
value of the first one. It creates new copy in memory and after it
the values of these variables will be next:
i = 10;
j = i;
There are a few more things written in the above example for
explaining the Reference Types in C#. At first, the variable ic1 of
IntClass is created using dynamic memory allocation. Then we
initialize the variable ic2 with value of ic1. This makes both the
variables ic1 and ic2 referring to the same address. If we change a
value of ic2, it automatically changes the value of ic1.
Enumerated types can be used to create some set of identifiers
that can have values of simple type. Let us see at example of
enum type:
Monday,
Tuesday,
Wensday,
Thursday,
Friday,
Saturday,
Sunday
using System;
class EnumSwitch
{
static void Main()
{
// create and initialize
// instance of enum type
Volume myVolume = Volume.Medium;
Fields and properties represent information that an object contains. Fields are like
variables because they can be read or set directly
using System;
propHold.SomeProperty = 5;
return 0;
}
}
Inheritance
When we need a class that has some properties and methods common to a previously
defined class, we can inherit the new class from the previously defined class. This
way, we need to define only those properties and methods of the new class. The
common properties and methods will be inherited from the old class.
using System;
class BankAccountPrivate
{
private string m_name;
using System;
class BankAccountProtected
{
public void CloseAccount()
{
ApplyPenalties();
CalculateFinalInterest();
DeleteAccountFromDB();
}
using System;
Polymorphism
When a derived class inherits from a base class, it gains all the methods, fields, properties and events
of the base class. To change the data and behavior of a base class, you have two choices: you can
replace the base member with a new derived member, or you can override a virtual base member.
Replacing a member of a base class with a new derived member requires the new keyword. If a base
class defines a method, field, or property, the new keyword is used to create a new definition of that
method, field, or property on a derived class. The new keyword is placed before the return type of a
class member that is being replaced. For example:
When the new keyword is used, the new class members are called instead of the base class members
that have been replaced. Those base class members are called hidden members. Hidden class
members can still be called if an instance of the derived class is cast to an instance of the base class.
For example:
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.
In order for an instance of a derived class to completely take over a class member from a base class,
the base class has to declare that member as virtual. This is accomplished by adding the virtual
keyword before the return type of the member. A derived class then has the option of using the
override keyword, instead of new, to replace the base class implementation with its own. For
example:
Fields cannot be virtual; only methods, properties, events and indexers can be virtual. When a derived
class overrides a virtual member, that member is called even when an instance of that class is being
accessed as an instance of the base class. For example:
BaseClass A = (BaseClass)B;
A.DoWork(); // Also calls the new method.
Virtual methods and properties allow you to plan ahead for future expansion. Because a virtual
member is called regardless of which type the caller is using, it gives derived classes the option to
completely change the apparent behavior of the base class.
Virtual members remain virtual indefinitely, no matter how many classes have been declared between
the class that originally declared the virtual member. If class A declares a virtual member, and class B
derives from A, and class C derives from B, class C inherits the virtual member, and has the option to
override it, regardless of whether class B declared an override for that member. For example:
public class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
using System;
Listing 9-1 shows the DrawingObject class. This will be the base class
for other objects to inherit from. It has a single method named Draw().
The Draw() method has a virtual modifier. The virtual modifier indicates
to derived classes that they can override this method. The Draw() method
of the DrawingObject class performs a single action of printing the
statement, "I'm just a generic drawing object.", to the console.
using System;
Listing 9-2 shows three classes. These classes inherit the DrawingObject
class. Each class has a Draw() method and each Draw() method has an
override modifier. The override modifier allows a method to override the
virtual method of its base class at run-time. The override will happen
only if the class is referenced through a base class reference. Overriding
methods must have the same signature, name and parameters, as the
virtual base class method it is overriding.
return 0;
}
}
Abstract classes may also define abstract methods. This is accomplished by adding the keyword
abstract before the return type of the method. For example:
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class.
A class inheriting an abstract method cannot access the original implementation of the method—in the
previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class
can force derived classes to provide new method implementations for virtual methods
interface interface-name
{
//members of the interface
}
Commonly, the name of the interface starts with the prefix `I' (though it is not a strict
rule). The following example illustrates how to define an interface:
Notice that the SomeMethod() method does not have any implementation. This is
because we do not use an interface directly in our program. We need a class or
structure that will implement the interface:
Here, the class MyClass implements the SomeMethod() method of the interface. An
interface is a type of contract that specifies that the class or structure inheriting the
interface must implement its members.
Interface is an abstract type. It is used only for declaring type with some abstract members. It
means members without implementations. Please, have a look at piece of code with a
declaration for a simple interface:
interface IMyInterface
{
void MethodToImplement();
}
Next feature that obviously needs to be explained is multiple inheritance using c# interfaces.
This can be done using child class that inherits from any number of c# interfaces. The
inheritance can also happen with a combination of a C# .Net class and c# interfaces. Now let
us see a small piece of code that demonstrate us multiple inheritance using only interfaces as
parent data types.
// INode members
}
The above example created a class ClonableNode. It implements all the functionality of
INode interface in the same way as it was done in Node class. Also it realizes Clone method
only one item of IClonable interface of .NET library.
Static Classes
A class can be declared static, indicating that it contains only static members. It is not possible to
create instances of a static class using the new keyword. Static classes are loaded automatically by
the .NET Framework common language runtime (CLR) when the program or namespace containing
the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it
is a common requirement to create a set of methods that do not act on instance data and are not
associated to a specific object in your code. You could use a static class to hold those methods.
Creating a static class is therefore much the same as creating a class that contains only static
members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance
members are accidentally added. The compiler will guarantee that instances of this class cannot be
created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a
constructor, although it is still possible to declare a static constructor to assign initial values or set up
some static state.
class CompanyInfo
{
public string GetCompanyName() { return "CompanyName"; }
public string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
These methods do not need to be attached to a specific instance of the class. Therefore, instead of
creating unnecessary instances of this class, you can declare it as a static class, like this:
Static Members
A static method, field, property, or event is callable on a class even when no instance of the class has
been created. If any instances of the class are created, they cannot be used to access the static
member. Only one copy of static fields and events exists, and static methods and properties can only
access static fields and static events. Static members are often used to represent data or calculations
that do not change in response to object state; for instance, a math library might contain static
methods for calculating sine and cosine.
Static class members are declared using the static keyword before the return type of the member, for
example:
Automobile.Drive();
int i = Automobile.NumberOfWheels;
Example
Here is an example of a static class that contains two methods that convert temperature from Celsius
to Fahrenheit and vice versa:
return fahrenheit;
}
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor
direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius
temperature: ");
F =
TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit:
{0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit
temperature: ");
C =
TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius:
{0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a
convertor.");
break;
}
}
}
It is possible to split the definition of a class or a struct, an interface or a method over two or more
source files. Each source file contains a section of the type or method definition, and all parts are
combined when the application is compiled.
Partial Classes
There are several situations when splitting a class definition is desirable:
• When working on large projects, spreading a class over separate files enables multiple
having to recreate the source file. Visual Studio uses this approach when it creates Windows
Forms, Web service wrapper code, and so on. You can create code that uses these classes
without having to modify the file created by Visual Studio.
• To split a class definition, use the partial keyword modifier, as shown here:
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the
namespace. All the parts must use the partial keyword. All the parts must be available at compile
time to form the final type. All the parts must have the same accessibility, such as public, private,
and so on.
If any part is declared abstract, then the whole type is considered abstract. If any part is declared
sealed, then the whole type is considered sealed. If any part declares a base type, then the whole
type inherits that class.
All the parts that specify a base class must agree, but parts that omit a base class still inherit the base
type. Parts can specify different base interfaces, and the final type implements all the interfaces listed
by all the partial declarations. Any class, struct, or interface members declared in a partial definition
are available to all the other parts. The final type is the combination of all the parts at compile time.
The following example shows that nested types can be partial, even if the type they are nested within
is not partial itself.
C#
Copy Code
class Container
{
partial class Nested
{
void Test() { }
}
partial class Nested
{
void Test2() { }
}
}
Using Constructors
Constructors are class methods that are executed when an object of a given type is created.
Constructors have the same name as the class, and usually initialize the data members of the new
object.
In the following example, a class named Taxi is defined by using a simple constructor. This class is
then instantiated with the new operator. The Taxi constructor is invoked by the new operator
immediately after memory is allocated for the new object.
class TestTaxi
{
static void Main()
{
Taxi t = new Taxi();
Console.WriteLine(t.isInitialized);
}
}
A constructor that takes no parameters is called a default constructor. Default constructors are
invoked whenever an object is instantiated by using the new operator and no arguments are provided
to new. For more information, see Instance Constructors (C# Programming Guide).
Unless the class is static, classes without constructors are given a public default constructor by the C#
compiler in order to enable class instantiation. For more information, see Static Classes and Static
Class Members (C# Programming Guide).
You can prevent a class from being instantiated by making the constructor private, as follows:
class NLog
{
// Private Constructor:
private NLog() { }
class CoOrds
{
public int x, y;
// constructor
public CoOrds()
{
x = 0;
y = 0;
}
}
This instance constructor is called whenever an object based on the CoOrds class is created. A
constructor like this one, which takes no arguments, is called a default constructor. However, it is
often useful to provide additional constructors. For example, we can add a constructor to the CoOrds
class that allows us to specify the initial values for the data members:
// tcA constructor with two arguments:
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
This allows CoOrd objects to be created with default or specific initial values, like this:
If a class does not have a default constructor, one is automatically generated and default values are
used to initialize the object fields, for example, an int is initialized to 0. For more information on
default values, see Default Values Table (C# Reference). Therefore, because the CoOrds class default
constructor initializes all data members to zero, it can be removed altogether without changing how
the class works. A complete example using multiple constructors is provided in Example 1 later in this
topic, and an example of an automatically generated constructor is provided in Example 2.
Instance constructors can also be used to call the instance constructors of base classes. The class
constructor can invoke the constructor of the base class through the initializer, as follows:
C#
Copy Code
class Circle : Shape
{
public Circle(double radius)
: base(radius, 0)
{
}
}
In this example, the Circle class passes values representing radius and height to the constructor
provided by Shape from which Circle is derived. A complete example using Shape and Circle
appears in this topic as Example 3.
Example 1
The following example demonstrates a class with two class constructors, one without arguments and
one with two arguments.
C#
Copy Code
class CoOrds
{
public int x, y;
// Default constructor:
public CoOrds()
{
x = 0;
y = 0;
}
class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);
Example 2
In this example, the class Person does not have any constructors, in which case, a default
constructor is automatically provided and the fields are initialized to their default values.
C#
Copy Code
public class Person
{
public int age;
public string name;
}
class TestPerson
{
static void Main()
{
Person person = new Person();
Example 3
The following example demonstrates using the base class initializer. The Circle class is derived from
the general class Shape, and the Cylinder class is derived from the Circle class. The constructor
on each derived class is using its base class initializer.
C#
Copy Code
abstract class Shape
{
public const double pi = Math.PI;
protected double x, y;
class TestShapes
{
static void Main()
{
double radius = 2.5;
double height = 3.0;
class NLog
{
// Private Constructor:
private NLog() { }
The declaration of the empty constructor prevents the automatic generation of a default constructor.
Note that if you do not use an access modifier with the constructor it will still be private by default.
However, the private modifier is usually used explicitly to make it clear that the class cannot be
instantiated.
Private constructors are used to prevent creating instances of a class when there are no instance
fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
If all the methods in the class are static, consider making the complete class static. For more
information see Static Classes and Static Class Members (C# Programming Guide).
Example
The following is an example of a class using a private constructor.
C#
Copy Code
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
Console.WriteLine("New count: {0}", Counter.currentCount);
Notice that if you uncomment the following statement from the example, it will generate an error
because the constructor is inaccessible because of its protection level:
Static Constructors
A static constructor is used to initialize any static data, or to perform a particular action that needs
performed once only. It is called automatically before the first instance is created or any static
members are referenced.
C#
Copy Code
class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;
• A static constructor is called automatically to initialize the class before the first instance is
• The user has no control on when the static constructor is executed in the program.
• A typical use of static constructors is when the class is using a log file and the constructor is
• Static constructors are also useful when creating wrapper classes for unmanaged code, when
• If a static constructor throws an exception, the runtime will not invoke it a second time, and
the type will remain uninitialized for the lifetime of the application domain in which your
program is running.
Example
In this example, class Bus has a static constructor. When the first instance of Bus is created (bus1),
the static constructor is invoked to initialize the class. The sample output verifies that the static
constructor runs only one time, even though two instances of Bus are created, and that it runs before
the instance constructor runs.
C#
Copy Code
public class Bus
{
// Static variable used by all Bus instances.
// Represents the time the first bus of the day starts its
route.
protected static readonly DateTime globalStartTime;
// Instance constructor.
public Bus(int routeNum)
{
RouteNumber = routeNum;
Console.WriteLine("Bus #{0} is created.", RouteNumber);
}
// Instance method.
public void Drive()
{
TimeSpan elapsedTime = DateTime.Now - globalStartTime;
// boxing
char ch = 'b';
object obj = ch;
Console.WriteLine("Char value is {0}",ch);
Console.WriteLine("Object value is {0}",obj);
Console.WriteLine();
This piece of code prints the same values of integer type variable and object type variable.
The opposite process to the boxing is un-boxing. An example for un-boxing is as follows.
// unboxing
float q = 4.6f;
object ob = q;
Console.WriteLine("Object value is {0}",ob);
float r = (float)ob;
Console.WriteLine("Float value is {0}",r);
So, it is main item of common data type creating and using. All sources are attached. To
compile and run it need to run .NET command line. Just type: csc DataTypes.cs. It creates
DataTypes.exe that can be run as standard executable file. You can download the sample
code here.
Exceptions
It is very difficult to find and debug the run-time errors. These
errors also called exceptions. Rules of good coding style say that
program must be able to handle any runtime error. Exception
generates an exception call at runtime. Exceptions in C# can be
called using two methods:
using System;
using System.IO;
class FinallyDemo
{
static void Main(string[] args)
{
FileStream outStream = null;
FileStream inStream = null;
try
{
outStream = File.OpenWrite("DestinationFile.txt");
inStream = File.OpenRead("BogusInputFile.txt");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (outStream != null)
{
outStream.Close();
Console.WriteLine("outStream closed.");
}
if (inStream != null)
{
inStream.Close();
Console.WriteLine("inStream closed.");
}
}
}
}
Reflection
Reflection is the feature in .Net, which enables us to get some
information about object in runtime. That information contains data
of the class. Also it can get the names of the methods that are
inside the class and constructors of that object.
10.Reflection
Reflection is the feature in .Net, which enables us to get some
information about object in runtime. That information contains data
of the class. Also it can get the names of the methods that are
inside the class and constructors of that object.
public TestDataType()
{
counter = 1;
}
public TestDataType(int c)
{
counter = c;
}
At first we should get type of object that was created. The following
C# .Net code snippet shows how to do it.
Console.WriteLine();
// get all the methods
Console.WriteLine("Methods:");
foreach( MethodInfo mf in methods )
{
Console.WriteLine(mf);
}
Think about how you use methods right now. You write an algorithm that
does its thing by manipulating the values of variables and calling methods
directly by name. What if you wanted an algorithm that was very flexible,
reusable, and allowed you to implement different functionality as the
need arises? Furthermore, let's say that this was an algorithm that
supported some type of data structure that you wanted to have sorted, but
you also want to enable this data structure to hold different types. If you
don't know what the types are, how could you decide an appropriate
comparison routine? Perhaps you could implement an if/then/else or
switch statement to handle well-known types, but this would still be
limiting and require overhead to determine the type. Another alternative
would be for all the types to implement an interface that declared a
common method your algorithm would call, which is actually a nice
solution. However, since this lesson is about delegates, we'll apply a
delegate solution, which is quite elegant.
You could solve this problem by passing a delegate to your algorithm and
letting the contained method, which the delegate refers to, perform the
comparison operation. Such an operation is performed in Listing 14-1.
using System;
class SimpleDelegate
{
Name[] names = new Name[5];
public SimpleDelegate()
{
names[0] = new Name("Joe", "Mayo");
names[1] = new Name("John", "Hancock");
names[2] = new Name("Jane", "Doe");
names[3] = new Name("John", "Doe");
names[4] = new Name("Jack", "Smith");
}
sd.PrintNames();
sd.PrintNames();
}
using System;
using System.Drawing;
using System.Windows.Forms;
// custom delegate
public delegate void Startdelegate();
class Eventdemo : Form
{
// custom event
public event Startdelegate StartEvent;
public Eventdemo()
{
Button clickMe = new Button();
clickMe.Parent = this;
clickMe.Text = "Click Me";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) /2,
(ClientSize.Height - clickMe.Height)/2);