C# Notes
C# Notes
Abbreviated as GAC, the Global Assembly Cache is a machine-wide store used to hold assemblies that are
intended to be shared by several applications on the machine. Each computer where the common language
runtime (CLR) is installed has a global assembly cache. The global assembly cache stores the assemblies
specifically designated to be shared by several applications on the computer.
The .NET Framework provides two tools for working with the cache. One is a Windows shell extension that
allows you to work with the cache using a Graphical User Interface (GUI). The other is a command line tool,
called the Global Assembly Cache tool (Gacutil.exe), that is typically used in build and test scripts.
C#
In C# types are divided into 2 broad categories.
Value Types - int, float, double, structs, enums etc
Reference Types Interface, Class, delegates, arrays etc
By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)
NULL coalescing operator:
Program without using NULL coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
if (TicketsOnSale == null)
{
AvailableTickets = 0;
}
else
{
AvailableTickets = (int)TicketsOnSale;
}
Console.WriteLine("Available Tickets={0}", AvailableTickets);
}
}
The above program is re-written using NULL coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
//Using null coalesce operator ??
AvailableTickets = TicketsOnSale ?? 0;
Console.WriteLine("Available Tickets={0}", AvailableTickets);
}
}
Datatype conversions
Example: Converting an int to a float will not loose any data and no exception will be
thrown, hence an implicit conversion can be done.
Where as when converting a float to an int, we loose the fractional part and also a
possibility of overflow exception. Hence, in this case an explicit conversion is required. For
explicit conversion we can use cast operator or the convert class in c#.
Implicit Conversion Example
using System;
class Program
{
public static void Main()
{
int i = 100;
// float is bigger datatype than int. So, no loss of
// data and exceptions. Hence implicit conversion
float f = i;
Console.WriteLine(f);
}
}
Explicit Conversion Example
using System;
class Program
{
public static void Main()
{
float f = 100.25F;
// Cannot implicitly convert float to int.
// Fractional part will be lost. Float is a
// bigger datatype than int, so there is
// also a possiblity of overflow exception
// int i = f;
// Use explicit conversion using cast () operator
int i = (int)f;
// OR use Convert class
// int i = Convert.ToInt32(f);
Console.WriteLine(i);
}
}
Difference between Parse and TryParse
1. If the number is in a string format you have 2 options - Parse() and TryParse()
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse()
returns a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse()
ARRAYS IN C#
Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices
to store or retrieve items from the array.
Polymorphism:
When a message can be processed in different ways is called polymorphism.
Polymorphism means many forms.
It allows you to invoke methods of derived class through base class reference
during runtime.
It has the ability for classes to provide different implementations of methods that
are called through the same name.
Compile time polymorphism is method and operators overloading. It is also called early
binding.
In method overloading method performs the different task at the different input
parameters.
Runtime time polymorphism is done using inheritance and virtual functions. Method
overriding is called runtime polymorphism. It is also called late binding.
When overriding a method, you change the behavior of the method for the derived
class. Overloading a method simply involves having another method with the same
prototype.
Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.
using System;
namespace method_overloading
{
class Program
{
public class Print
{
Note: In the code if you observe display method is called two times. Display method will
work according to the number of parameters and type of parameters.
Use method overloading in situation where you want a class to be able to do something,
but there is more than one possibility for what information is supplied to the method that
carries out the task.
You should consider overloading a method when you for some reason need a couple of
methods that take different parameters, but conceptually do the same thing.
Properties in C#:
In C#, properties are nothing but natural extension of data fields. They
are usually known as 'smart fields' in C# community. We know that data
encapsulation and hiding are the two fundamental characteristics of any
object oriented programming language.In C#, data encapsulation is
possible through either classes or structures. By using various access
modifiers like private, public, protected, internal etc it is possible to
control the accessibility of the class members.
Usually inside a class, we declare a data field as private and will provide a
set of public SET and GET methods to access the data fields. This is a
good programming practice, since the data fields are not directly
accessible out side the class. We must use the set/get methods to access
the data fields.
using System;
class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that a property should have at least one accessor, either set or
get. The set accessor has a free variable available in it called value, which
gets created automatically by the compiler. We can't declare any variable
with the name value inside the set accessor.
We can do very complicated calculations inside the set or get accessor.
Even they can throw exceptions.
Since normal data fields and properties are stored in the same memory
space, in C#, it is not possible to declare a field and property with the
same name.
Static Properties
C# also supports static properties, which belongs to the class rather than
to the objects of the class. All the rules applicable to a static member are
applicable to static properties also.
The following program shows a class with a static property.
//C# : static Property
//Author: [email protected]
using System;
class MyClass
{
private static int x;
public static int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that set/get accessor of static property can access only other
static members of the class. Also static properties are invoking by using
the class name.
Properties & Inheritance
The properties of a Base class can be inherited to a Derived class.
//C# : Property : Inheritance
//Author: [email protected]
using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}
Abstract Properties
A property inside a class can be declared as abstract by using the
keyword abstract. Remember that an abstract property in a class carries
no code at all. The get/set accessors are simply represented with a
semicolon. In the derived class we must implement both set and get
assessors.
If the abstract class contains only set accessor, we can implement only set
in the derived class.
The following program shows an abstract property in action.
//C# : Property : Abstract
//Author: [email protected]
using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}
Structures in C#:
A structure in C# is simply a composite data type consisting of a number
elements of other types. A C# structure is a value type and the instances or
objects of a structure are created in stack. The structure in C# can contain
fields, methods, constants, constructors, properties, indexers, operators and
even other structure types.
Where the modifier can be private, public, internal or public. The struct is the
required keyword.
For example
struct MyStruct
{
public int x;
public int y;
}
The individual members of a struct can be accessed by using the dot (.)
operator as showing below.
ms.x = 10;
ms.y = 20;
Remember that unlike classes, the strcut object can also be created without
using the new operator.
MyStruct ms;
But in this case all fields of the struct will remain unassigned and the object
can't be used until all of the fields are initialized.
Structs & Fields
A struct in C# can contain fields. These fields can be declared as private,
public, internal. Remember that inside a struct, we can only declare a field.
We can't initialize a field inside a struct. However we can use constructor to
initialize the structure fields.
The following is not a valid C# struct and the code will not compile, since the
fields inside the structure are trying to initialize.
struct MyStruct
{
int x = 20; // Error its not possible to initialize
int y = 20; // Error its not possible to initialize
}
However a struct can contain static fields, which can be initialized inside the
struct. The following example shows the use of static fields inside a struct.
// Author: [email protected]
using System;
struct MyStruct
{
public static int x = 25;
public static int y = 50;
}
class MyClient
{
public static void Main()
{
int sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}
}
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.SetXY(100,200);
MyStruct.ShowSum();
}
}
The methods inside a struct can also be overloaded as like inside a class. For
example
// Author:[email protected]
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public void SetXY(int i)
{
x = i;
y = i;
}
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct();
MyStruct ms2 = new MyStruct();
ms1.SetXY(100,200);
ms2.SetXY(500);
}
}
{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
ms1.ShowXY();
}
}
struct Complex
{
private int x;
private int y;
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}
Inheritance:
When a class acquire the property of another class is known as inheritance.
Inheritance is process of object reusability.
For example, A Child acquire property of Parents.
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("Child Constructor.");
}
public static void Main()
{
ChildClass child = new ChildClass();
child.print();
}
}
Output:
Parent Constructor.
Child Constructor.
I'm a Parent Class.
Polymorphism:
Constructors:
In simple terms, Constructor is a special kind of method with class name as
method name and gets executed when its (class) object is created.
Constructors can be classified into 5 types
1.
Default Constructor
2.
Parameterized Constructor
3.
Copy Constructor
4.
Static Constructor
5.
Private Constructor
In simple words a copy constructor means a constructor which copies data of one object into
another object.
class employee
{
private string name;
private int age;
public employee(string name, int age) // Instance constructor.
{
this.name = name;
this.age = age;
}
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}
public string Details
// Get deatils of employee
{
get
{
return " The age of " + name +" is "+ age.ToString();
}
}
}
class empdetail
{
static void Main()
{
employee emp1 = new employee("Vithal", 23); // Create a new
employee object.
employee emp2 = new employee(emp1);
// here is emp1 details is
copied to emp2.
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}
}
Static Constructor : You can create a constructor as static and when a
constructor is created as static, it will be invoked only once for any number of
instances of the class and it is during the creation of first instance of the class or
the first reference to a static member in the class. Static constructor is used to
initialize static fields of the class and to write the code that needs to be executed
only once.
namespace ProgramCall
{
class Test3
{
public Test3()
{
Console.WriteLine("Instance Constructor");
}
static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
Test3 T1 = new Test3(); // Both the constructors are invoked
Test3 T2 = new Test3(); // When this object is created only instance
constructor is invoked.
Console.Read();
}
}
}
Output Static Constructor
Instance Constructor
Instance Constructor
Private Constructor : You can also create a constructor as private. When a class
contains at least one private constructor, then it is not possible to create an
instance for the class. Private constructor is used to restrict the class from being
instantiated when it contains every member as static.
Note
A static constructor should not be declared with any access modifier.
A static constructor does not accept parameters
A static constructor is called automatically.
There is no way to call a static constructor directly.
Cant stop the execution of Static constructor
class test4:test2
{
public override int mul(int i, int j)
{
return i+j;
}
}
class myclass
{
public static void main (string[] args)
{
test2 ob= new test4();
int a = ob.mul(2,4);
test1 ob1= new test2();
int b = ob1.mul(4,2);
test1 ob2= new test3();
int c = ob2.mul(4,2);
Console.Write("{0},{1},{2}",a,b,c);
Console.ReadLine ();
}
}
Interfaces:
An interface looks like a class, but has no implementation. The only thing it contains are
declarations of events, indexers, methods and/or properties. The reason interfaces only
provide declarations is because they are inherited by structs and classes, that must
provide an implementation for each interface member declared.
So, what are interfaces good for if they don't implement functionality? They're great for
putting together plug-n-play like architectures where components can be interchanged at
will. Since all interchangeable components implement the same interface, they can be
used without any extra programming. The interface forces each component to expose
specific public members that will be used in a certain way.
Because interfaces must be implemented by derived structs and classes, they define a
contract.
interface IMyInterface
{
void MethodToImplement();//Abstract Method signature.
}
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer obj = new InterfaceImplementer();
obj.MethodToImplement();
}
public void MethodToImplement()
{
//Abstract Method Implementation
}
}
ODDEVEN.cs
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace InterFaceDemo
{
interface IOne
{
void ONE();//Pure Abstract Method Signature
}
interface ITwo
{
void TWO();
}
interface IThree:IOne
{
void THREE();
}
interface IFour
{
void FOUR();
}
interface IFive:IThree
{
void FIVE();
}
interface IEVEN:ITwo,IFour
{
}
class ODDEVEN:IEVEN,IFive//Must Implement all the abstract method, in
Derived class.
{
public void ONE()//Implementation of Abstract Method.
{
Console.WriteLine("This is ONE");
}
public void TWO()
{
Console.WriteLine("This is TWO");
}
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace InterFaceDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is ODD");
IFive obj1 = new ODDEVEN();
obj1.ONE();
obj1.THREE();
obj1.FIVE();
Console.WriteLine("\n\nThis is EVEN");
IEVEN obj2 = new ODDEVEN();
obj2.TWO();
obj2.FOUR();
Console.ReadLine();
}
}
}
The following is the output:
Purposes of Interfaces
class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
}
}
{
public void Display()
{
Console.WriteLine("Class1 Display Method.");
}
//Implicit interface implementation
public void interface1_method()
{
Console.WriteLine("Iinterface_1 Method Implicit interface implementation.");
}
//Explicit interface implementation
void Iinterface_1.interface1_method()
{
Console.WriteLine("Iinterface_1 Method Explicit interface implementation.");
}
}
class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
//Call Implicit interface method
objClass1.interface1_method();
Console.ReadLine();
}
}
Output: Class1 Display Method.
Iinterface_1 Method Implicit interface implementation.
Note:
In the picture above, when you type objClass1., then only interface1_method will be
class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
//Call Implicit interface method
objClass1.interface1_method();
//Call Explicit interface method
Iinterface_1 obj_1 = new Class1();
obj_1.interface1_method();
Console.ReadLine();
}
}
Output: Class1 Display Method.
Iinterface_1 Method Implicit interface implementation.
Iinterface_1 Method Explicit interface implementation.
Delegates:
There might be situation in which you want to pass methods around to other methods.
For this purpose we create delegate.
A delegate is a class that encapsulates a method signature. Although it can be used in
any context, it often serves as the basis for the event-handling model in C# but can be
used in a context removed from event handling (e.g. passing a method to a method
through a delegate parameter).
{
//Create an Instance of MulticastDelegate
//that points to MyClass.Add().
MulticastDelegate del = new MulticastDelegate(MyClass.Add);
//using the same instance of MulticastDelegate
//to call MyClass.Multibly() by adding it to it's
//invocation list.
del += new MulticastDelegate(MyClass.Multiply);
//Invoke Add() and Multiply() methods using the delegate.
//Note that these methods must have a void return vlue
Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");
del(5, 5);
//removing the Add() method from the invocation list
del -= new MulticastDelegate(MyClass.Add);
Console.WriteLine("\n\n****Add() Method removed.****\n\n");
//this will invoke the Multibly() method only.
del(5, 5);
}
}
}
EVENTS:
Windows based applications are message based. Application is communicating with
windows and windows are communicating with application by using predefined
messages. .Net wraps up the messages with 'EVENTS'. And .Net reacting a particular
message by handling events. Events are the message sent by an object to indicate the
occurrence of an event. Event can also be defined as a member that enables an object
to provide notification. Events provide a powerful means of inter-process
communication. Events are used for communication between Objects. Communication
between Objects is done by events.
Delegates are used as the means of wiring up the event when the message is received
by the application.
Event Receiver
The event receiver may be
1. An application
2. An Object
3. A component
Event receiver gets modified when something happens.
Event Sender
The Event sender may be
1. An assembly in an application
2. An object
3. System events like Mouse event or keyboard entry.
Event sender's job is to raise the Event. Event sender doesn't know anything about,
whom and what the receiver is. To handle the event, there would be some method
inside event receiver. This Event handler method will get executed each time when
event is registered to be raised.
Here DELEGATE comes into action, because Sender has no idea who the
receiver will be.
The PROCESS of hooking up the event handler is known as WIRING UP an
Event.
A simple example of wiring up is CLICK EVENT.
The EventHandler Delegate
This Delegate is defined in .Net framework. It is defined in System namespace. All of the
events that are defined in .Net framework will use it.
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace EventExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Adding EventHandler to Click event of Buttons
btn1.Click +=new EventHandler(Button_Click);
btn2.Click +=new EventHandler(Button_Click);
}
// Button Click Method , here signature of this is same as of Eventhandler
private void Button_Click(Object sender, EventArgs e)
{
string str;
if (sender == btn1)
{
str = btn1.Text;
MessageBox.Show(str+" Clicked ");
}
if (sender == btn2)
{
str = btn2.Text;
}
}
When the above code is compiled and executed, it produces the following
result:
TempIsZeroException: Zero Temperature found
ENUMS:
What is enum?
An enum is a value type with a set of related named constants often referred to as an
enumerator list. The enum keyword is used to declare an enumeration. It is a primitive
data type, which is user defined.
Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has
to becast.
enum is used to create numeric constants in .NET framework. All member of enum are of
enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration elements is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased
by 1.
enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Program to demonstrate how to create and Use an Enum:
using System;
namespace example_enum
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday
}
static void Main(string[] args)
{
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Sunday,DayofWeek.Sunday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Monday,DayofWeek.Monday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Tuesday,DayofWeek.Tuesday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Wednesday,DayofWeek.Wednesday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Thursday,DayofWeek.Thursday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Friday,DayofWeek.Friday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Saturday,DayofWeek.Saturday);
Console.ReadLine();
}
}
}
enums are not for end-user, they are meant for developers.
enums are strongly typed constant. They are strongly typed, i.e. an enum of one
type may not be implicitly assigned to an enum of another type even though the
underlying value of their members are the same.
Enumerations (enums) make your code much more readable and understandable.
enum values are fixed. enum can be displayed as a string and processed as an
integer.
The default type is int, and the approved types are byte, sbyte, short, ushort,
uint, long, and ulong.
Every enum type automatically derives from System.Enum and thus we can use
System.Enum methods on enums.
Enums are value types and are created on the stack and not on the heap.
Excellent
Default
Good
ACCESS MODIFIERS:
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the
concept of encapsulation, which promotes the idea of hiding functionality. Access
modifiers allow you to define who does or doesn't have access to certain features.
Modifier
Description
public
private
protected
internal
Access is limited
exclusively to classes
defined within the current
project assembly
protected
internal
ATTRIBUTES:
What is an attributes ?
An attribute is a information which marks the elements of code such as a class or
REFLECTION:
Introduction
In C#, Reflection is a process by which we can get the detailed information from
assembly, like about method, constructor, attribute, property, module, global class,
parameters, and many more at run time. Reflection can modify structure and behavior of
a computer program.
What is Reflection in C#
"Reflection is a mechanism by which we can get metadata information from assembly at
run time."
When use Reflection
If we want to know assembly information at run time ,then we use reflection. Reflection
are used for data binding in .NET Framework. It is also used for testing in .NET
Framework.
How to use
There are System.Reflection is the namespace for the reflection. System.Reflection
namespace defines the assembly module, MemberInfo, PropertyInfo, MethodInfo,
ConstructorInfo, FieldInfo, EventInfo etc.
The System.Type is the base class for reflection. System.Type find the type name,
namespace, module type etc. System.Type is also an abstract class .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace reflection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int n = 45;
//string n = "vineet";
System.Type t = n.GetType();
MessageBox.Show(t.ToString());//Display type of varible
MessageBox.Show(t.Name);//Display name of variable
MessageBox.Show(t.Namespace);//Display namespace by name
MessageBox.Show(t.IsArray.ToString());//Display boolean value
MessageBox.Show(t.IsClass.ToString());//Display boolean value
MessageBox.Show(t.Module.ToString());//Display module(library) of assembly
MessageBox.Show(t.MemberType.ToString());//Display membertype by name
MessageBox.Show(t.GetProperties().ToString());//Display property by name
MessageBox.Show(t.GetType().ToString());//Display type defined in assembly
MessageBox.Show(t.GetMethods().ToString());//Display method by name
MessageBox.Show(t.GetInterfaces().ToString());//Display interface by name
MessageBox.Show(t.FullName.ToString());//Display type of variable by name
MessageBox.Show(t.BaseType.ToString());//Display base type
MessageBox.Show(t.Attributes.ToString());//Display attribute by name
MessageBox.Show(t.Assembly.ToString());//Display assembly by name
MessageBox.Show(t.AssemblyQualifiedName.ToString());//Display
AssemblyQualifiedName
System.Reflection.Assembly o =
System.Reflection.Assembly.Load("mscorlib.dll");
MessageBox.Show(o.GetName().ToString());//Display information
about mscorlib assembly
object obj = o.GetType();
MessageBox.Show(obj.ToString());//Display name of runtime assembly
ConstructorInfo[] ci = t.GetConstructors();//Display information about
constructors
foreach (ConstructorInfo i in ci)
{
MessageBox.Show(i.ToString());
}
MethodInfo[] mi = t.GetMethods();//Display information about methods
foreach (MethodInfo i in mi)
{
MessageBox.Show(i.ToString());
}
PropertyInfo[] pi = t.GetProperties();//Display information about properties
foreach (PropertyInfo i in pi)
{
MessageBox.Show(i.ToString());
}
MemberInfo[] mf = t.GetMembers();//Display information about members
foreach (MemberInfo i in mf)
{
MessageBox.Show(i.ToString());
}
EventInfo[] ei = t.GetEvents();//Display information about events
foreach (EventInfo i in ei)
{
MessageBox.Show(i.ToString());
}
FieldInfo[] fi= t.GetFields();//Display information about fields
foreach (FieldInfo i in fi)
{
MessageBox.Show(i.ToString());
}
}
}
}
COLLECTIONS:
Introduction
It is just like as array ,but always dynamic and can hold any values unlike array. It is a
data structure that holds data in many different ways. The collection class is defined in
the System.Collections namespace. There are five types of collections in data structure.
1.Hastable
2.Arraylist
3.Linkedlist
4.Stack
5.Queue
But mostly use of two types collections in C#,they are Hastable and Arraylist. Here we
will discuss about only Hastable and Arraylist.
1. Hastable
Hastable have two values i.e. key(id) and item(value).
Output (all values using foreach loop) looks like the below image.
code description
In the above code first of all we make the object of hastable i.e. hs. After that we add
the key and value using the hs object in the hastable. If we print the only one value then
we will give your key(id), which is shown above. If we print the all values then we use
foreach loop.
2. ArrayList
Arraylist have only one values i.e. item(value) not a key(id).
Output (all values using foreach loop) looks like the below image.
0
code description
In the above code first of all we make the object of Arraylist i.e. 'al'. After that we add
the value using the 'al' object in the Arraylist. If we print the only one value then we will
give index number, which is shown above. If we print the all values then we use foreach
loop.
Summary
Collections are very important for stored data in the array and list. Collections solves the
many problem like as fixed array ,linked list etc. So collections are very useful for solving
these problems.
GENERICS:
Introduction:
Generics give you the ability to create generic methods or a generic type by
defining a placeholder for method arguments or type definitions, that are
specified at the time of invoking the generic method or creating the generic
type.
Why Generics?
As you may know, the ArrayList collection can receive and return only an
Object type, so the runtime will convert the value type (stack-allocated)
automatically via boxing operation into an Object (heap-allocated) as in the
following:
ArrayList intList = new ArrayList();
//add a value type to the collection(boxing)
intList.Add(5);
To retrieve the value from the ArrayList you must unbox the heap-allocated
object into a stack-allocated integer using a casting operation.
//unboxing
int x = (int)intList[0];
The problem with the stack/heap memory transfer is that it can have a big
impact on performance of your application because when you use boxing and
unboxing operations the following steps occur:
1. A new object must be allocated on the managed heap.
2. The value of the stack-allocated type must be transferred into that
memory location.
3. When unboxed, the value stored on the heap must be transferred back
to the stack.
4. The unused object on the heap will be garbage collected.
Now consider that your ArrayList contained thousands of integers that are
manipulated by your program, this for sure will have an affect on your
application performance.
Custom Collections:
Assume that you need to create a custom collection that can only contain
objects of the Employee type.
{
//boxing
alEmployees.Add(e);
}
//get the employee type
public Employee GetEmployee(int index)
{
//unboxing
return (Employee)alEmployees[index];
}
//to use foreach
IEnumerator IEnumerable.GetEnumerator()
{
return alEmployees.GetEnumerator();
}
}
The problem here is that if you have many types in you application then you
need to create multiple custom collections, one for each type. And as you can
see, we also have the problem of boxing and unboxing here.
All problems you saw previously can be solved using generics, so let's see
what we can do.
The System.Collections.generic namespace
You can find many generic collections in the System.Collections.Generic just
like:
1. List<T>
2. Dictionary<K, V>
3. Queue<T>
4. Stack<T>
Generic collections allow you to delay the specification of the contained type
until the time of creation.
By using the generic collection you avoid performance problems of the
boxing and unboxing operations and don't need to create a custom collection
Queue<T>
Queue<T> is a generic collection that represents a first-in, first-out (FIFO)
collection of objects. It is just like the non-generic collection Queue.
The following is an example of a Queue<T>:
//A generic Queue collection
Queue<int> intQueue = new Queue<int>();
//Add an int to the end of the queue
//(no boxing)
intQueue.Enqueue(5);
Stack<T>
Stack<T> is a generic collection that represents a last-in-first-out (LIFO)
collection of instances of the same arbitrary type. It is just like the nongeneric collection Stack.
The following is an example of a Stack<T>:
Stack<int> intStack = new Stack<int>();
//Insert an int at the top of the stack
//(no boxing)
intStack.Push(5);
//Returns the int at the top of the stack
//without removing it.
//(no unboxing)
int x = intStack.Peek();
//Removes and returns the int at the top of the stack
//(no unboxing)
int y = intStack.Pop();
Dictionary<K, V>
Dictionary<K, V> is a generic collection that contains data in Key/Value
pairs, it is just like the non-generic collection Hashtable.
The following is an example of a Dictionary<K, V>:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
//Add the specified key and value to the dictionary
dictionary.Add("Key", "Value");
//Removes the value with the specified key from the dictionary
dictionary.Remove("Key");
//get the number of the Key/Value pairs contained in the dictionary
int count = dictionary.Count;
Boxing
Implicit conversion of a value type (int, char etc.) to a reference type (object), is
known as Boxing. In boxing process, a value type is being allocated on the heap
rather than the stack.
Unboxing
Explicit conversion of same reference type (which is being created by boxing
process); back to a value type is known as unboxing. In unboxing process, boxed
value type is unboxed from the heap and assigned to a value type which is being
allocated on the stack.
For Example
1. // int (value type) is created on the Stack
2. int stackVar = 12;
3.
4. // Boxing = int is created on the Heap (reference type)
5. object boxedVar = stackVar;
6.
7. // Unboxing = boxed int is unboxed from the heap and assigned to an int
stack variable
8. int unBoxed = (int)boxedVar;
1. int i = 10;
2. ArrayList arrlst = new ArrayList();
3.
4. //ArrayList contains object type value
5. //So, int i is being created on heap
6. arrlst.Add(i); // Boxing occurs automatically
7.
8. int j = (int)arrlst[0]; // Unboxing occurs
String
String is immutable, Immutable means if you create string object then you cannot
modify it and It always create new object of string type in memory.
Example
string strMyValue = "Hello Visitor";
// create a new string instance instead of changing the old one
strMyValue += "How Are";
strMyValue += "You ??";
Stringbuilder
StringBuilder is mutable, means if create string builder object then you can perform any
operation like insert, replace or append without creating new instance for every time.it
will update string at one place in memory doesnt create new space in memory.
Example
StringBuilder sbMyValue = new StringBuilder("");
sbMyValue.Append("Hello Visitor");
sbMyValue.Append("How Are You ??");
string strMyValue = sbMyValue.ToString();
PARTIAL CLASSES:
It is possible to split the definition of a class or a struct, or an interface over two or more
source files. Each source file contains a section of the class definition, and all parts are
combined when the application is compiled.
When working on large projects, spreading a class over separate files allows multiple
programmers to work on it simultaneously.
When working with automatically generated source, code can be added to the class
without having to recreate the source file. Visual Studio uses this approach when
creating Windows Forms, Web Service wrapper code, and so on. You can create code
that uses these classes without having to edit the file created by Visual Studio.
Example
I will develop an example that explains how to use a partial class in your project. Suppose
you are working with LINQ to SQL in your application. So you create a data context, in
other words a .dbml file and drag and drop the necessary tables. Each table creates a
partial class in the data context designer file and each table field becomes a property for
the table. Suppose you have a "Person" table that has the three fields "Id","Name" and
"DateOfBirth" and you want to show the age of each person in a grid view. What will you
do? If you add a new column to the table for age in database for the "Person" table then
it fails the normalization rule so you should not do that. If you add a new property to
auto-generated code then it will not be mapped to the database. So you need to create a
partial class portion in a separate source file that has the "Age" property. This "Age"
property calculates the age of the person when you bind a person list to the grid view.
Let's see each step-by-step.
3. Right-click on the project in the Solution Explorer then go to "Add" and click on
"Class".
4. Choose "LINQ to SQL Classes" from the list and provide the name "Person" for the
DBML name. Then click on "Add".
5. Drag the User table from the database in the Server Explorer and drop onto the
O/R Designer surface of the "Person.dbml" file.
6. Create a partial class part that has the "Age" property to calculate the age. This
file is named "PersonExtension.cs".
using System;
namespace PartialClassExample
{
public partialclass Person
{
public int Age
{
get { returnConvert.ToInt32(System.DateTime.UtcNow.Date.Year _DateOfBirth.Value.Year); }
}
}
}
<
%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="PersonUI.aspx.cs"
Inherits="PartialClassExample.PersonUI"%>
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
<title></title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:GridViewID="gridPerson"runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
8. Write code for the "Page_Load" event to bind a grid view by person list in the code
behind file.
using System;
using System.Linq;
namespace PartialClassExample
{
public partialclass PersonUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (PersonDataContext context =new PersonDataContext())
{
var query = from person in context.GetTable<Person>()
select new
{
person.Id,
person.Name,
person.DateOfBirth,
person.Age
};
var content = query.ToList();
gridPerson.DataSource = content;
gridPerson.DataBind();
}
}
}
}
9. Run the application, you will see the Age column in the grid view that shows the
age of each person. Let's see that in Figure 1.3.
INDEXERS
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept
known as Indexers which are used for treating an object as an array. The indexers are
usually known as smart arrays in C#. They are not essential part of object-oriented
programming.
An indexer, also called an indexed property, is a class property that allows you to access
a member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of
that class can be accessed using the [] array access operator.
Creating an Indexer
<modifier> <return type> this [argument list]
{
get
{
// your get block code
}
set
{
// your set block code
}
}
In the above code:
<modifier>
can be private, public, protected or internal.
<return type>
can be any valid C# types.
this
this is a special keyword in C# to indicate the object of the current class.
[argument list]
The formal-argument-list specifies the parameters of the indexer.
Important points to remember on indexers:
Indexers are implemented through get and set accessors for the [ ] operator.
Indexers are accessed using indexes where as properties are accessed by names.
Indexer are defined in pretty much same way as properties, with get and set functions.
The main difference is that the name of the indexer is the keyword this.
Following program demonstrate how to use indexer.
using System;
namespace Indexer_example1
{
class Program
{
class IndexerClass
{
private string[] names = new string[10];
public string this[int i]
{
get
{
return names[i];
}
set
{
names[i] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass Team = new IndexerClass();
Team[0] = "Rocky";
Team[1] = "Teena";
Team[2] = "Ana";
Team[3] = "Victoria";
Team[4] = "Yani";
Team[5] = "Mary";
Team[6] = "Gomes";
Team[7] = "Arnold";
Team[8] = "Mike";
Team[9] = "Peter";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Team[i]);
}
Console.ReadKey();
}
}
}
Properties
keyword.
indexes.
names.
can't be static.
indexer.
parameter.
parameter.
Indexers are commonly used for classes, which represents some data structure, an
array, list, map and so on.
The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is
specified as the base class of another class.
1. A class, which restricts inheritance for security reason is declared, sealed class.
2. Sealed class is the last class in the hierarchy.
3. Sealed class can be a derived class but can't be a base class.
4. A sealed class cannot also be an abstract class. Because abstract class has to
provide functionality and here we are
restricting it to inherit.
Practical demonstration of sealed class
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace sealed_class
{
class Program
{
public sealed class BaseClass
{
public void Display()
{
Console.WriteLine("This is a sealed class which can;t be further
inherited");
}
}
public class Derived : BaseClass
{
// this Derived class can;t inherit BaseClass because it is sealed
}
static void Main(string[] args)
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}
}
}
Sealed Methods
Sealed method is used to define the overriding level of a virtual method.
Sealed keyword is always used with override keyword.
Practical demonstration of sealed method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_method
{
class Program
{
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Virtual method");
}
}
public class DerivedClass : BaseClass
{
// Now the display method have been sealed and can;t be overridden
public override sealed void Display()
{
Console.WriteLine("Sealed method");
}
}
//public class ThirdClass : DerivedClass
//{
//
//
//
which is
//
//}
FILE I/O :
File handling is a very crucial and important feature for many enterprise applications
around us. To support this feature Microsoft .NET Framework offers the System.IO
namespace, that provides various classes to enable the developers to do I/O.
In this article, you will learn how to work with classes in the System.IO namespace for
reading data from and writing data to files. The System.IO namespace also provides
features to support manipulation of files and directories of the operating systems file
system.
Objectives
The "ReadAllLines" method reads all the contents of a file and stores each line at
a new index in an array of string type.
The "ReadAllBytes" method reads the contents of a file as binary data and stores
the data in a byte array.
string filePath = @"C:\MyData\TestFile.txt";
byte[] testDataRawBytes = File.ReadAllBytes(filePath);
Each of these methods enable the developer to read the contents of a file and load into
memory. The ReadAllText method will enable the developer to cache the entire file in
memory via a single operation. Whereas the ReadAllLines method will read line-by-line
into an array.
Writing Data to Files
The File class also provides methods for writing various types of data to a file. For each
of the various types of data you can write, the File class provides two methods. If the
specified file does not exist, then the Writexxx methods create a new file with the new
data. If the file does exist then the Writexxx methods overwrite the existing file with the
new data. If the specified file does not exist then the Appendxxx methods also create a
new file with the new data.
However, if the file does exist then the new data is written to the end of the existing file.
The following list describes some of these methods:
The "WriteAllText" method enables the developers to write the contents of string
variable into a file. If the file exists, its contents will be overwritten. The following
code example shows how to write the contents of a string named settings to a
new file named settings.txt.
string filePath = @"C:\MyData\TestFile.txt";
string data = "C# Corner MVP & Microsoft MVP;";
File.WriteAllText(filePath, data);
Note: The overwrite parameter passed to the Copy method call indicates that the copy
process should overwrite an existing file if it exists at the destination path. If you pass
false to the Copy method call, and the file already exists then the Common Language
Runtime (CLR) will throw a System.IO.IOException.
The "Delete" method deletes an existing file from the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
File.Delete(sourceFilePath);
The "Exists" method checks whether a file exists on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
bool doesFileExist = File.Exists(sourceFilePath);
The "GetCreationTime" method obtains the date time stamp that describes when
a file was created, from the metadata associated with the file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
DateTime fileCreatedOn = File.GetCreationTime(sourceFilePath);
Once the instance of the FileInfo class is created, you can use the properties and
methods to interact with the file. The following list describes some of these properties
and methods.The "CopyTo" method enables the developers to copy an existing file to a
different directory on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overwrite = true;
FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.CopyTo(destinationFilePath, overwrite);
Note: The overwrite parameter in the CopyTo method indicates that the copy process
should overwrite an existing file if it exists at the specified destination file path. If you
pass false to the CopyTo method, and the file already exists then the CLR will throw a
System.IO.IOException.
The "DirectoryName" property enables the developers to get the directory path to
the file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
string directoryPath = fInfo.DirectoryName;
// returns C:\MyData
The "Exists" method enables the developers to determine if the specified file
exists within the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExists = fInfo.Exists;
The "Extension" property enables you to get the file extension of a file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExtn = fInfo.Extension;
The "Length" property enables the developers to get the length of the file in
bytes.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
long length = fInfo.Length;
The .NET Framework class library provides the Directory and DirectoryInfo classes for
such operations.
Using Directory class to manipulate directories
Similar to the File class, the "Directory" class provides static methods that enable you to
interact with directories, without instantiating a directory-related object in your code.
Note: The deleteRecursively parameter passed into the Delete method specifies
whether the delete process should delete any content that may exist in the
directory. If you pass false into the Delete method, and the directory is not empty
then the CLR will throw a System.IO.IOException.|
The "GetFiles" method gets a list of all the files within a specific directory on the
file system.
string sourceDirPath = @"C:\MyData\Data";
string[] files = Directory.GetFiles(sourceDirPath);
The "DirectoryInfo" class provides instance members that enable you to access directory
metadata and manipulate the directory structure.
Using DirectoryInfo class to manipulate directories.
The "DirectoryInfo" class acts as an in-memory representation of a directory. Before you
can access the properties and execute the methods that the DirectoryInfo class
exposes, you must create an instance of the class.
Instantiating the DirectoryInfo Class
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
When you have created an instance of the DirectoryInfo class, you can then use its
properties and methods to interact with the directory. The following list describes some
of these properties and methods:
The "FullName" property gets the full path to the directory. The following example
shows how to get the full path to the tempData directory.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
string fullPath = directory.FullName;
The "GetFiles" method gets a list of all the files within a specific directory on the
file system. In contrast to the static File.GetFiles method, this instance method
returns an array of type
FileInfo, that enables you to use each of the instance properties for each file.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
FileInfo[] subFiles = directory.GetFiles();
ANONYMOUS METHODS:
An anonymous method is a block of code that is used as the parameter for the
Delegate.Anonymous method allows coder to pass block of code rather than the name
of the method. Creating a anonymous method is a way to pass a code block as delegate
parameter.
Benefits:
1. To reduce code the amount of code
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace ConsoleApplication4
{
class Program
{
// Decelaring Delegate
public delegate void Display(String msg);
static void Main(string[] args)
{
// Delegate using anonymous method
Display del = delegate(string par)
Display del = delegate(string par)
{
Console.WriteLine("{0}", par);
};
// Invoking delegate
del("Christ");
Console.ReadLine();
}
}
}
In above code, Christ will get display as output. In above code, block of code is getting
passes as argument of delegate rather than name of the method.
Scope of the variable
The scope of variable of an anonymous method is the anonymous method block.
Anonymous method does not help speeding up the execution process because
for block of code, .Net generates the Anonymous name.