C# Console
C# Console
An d
C#.NET
Hour 50 Setup Project Development, Installing and Un-installing the projects Page 496
Backend tool: It acts as storage mechanism. The data related to the project
will be stored in this backend tool. It allows us to create and store the databases.
Ex: Oracle, SQL Server, My SQL, Sybase, DB2 etc.
It was released by Microsoft Corporation in 2002. At this year, in the programming world,
we have so many languages like Basic, COBOL, Pascal, Fortran, C, C++, VB, VC++ etc.
But if you observe these languages, each and every language is having its own
Language: It acts as interface (mediator) between the programmer and the system. It
offers some rules and regulations for writing the programs. It also offers some library,
which is required for writing the programs. Obviously, the collection of programs is called
as ―Software‖.
.NET Framework) provides support for 3 Microsoft developed languages and several
other languages from other vendors.
Modules of .NET
It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for server
side logic implementation.
It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for logic
implementation.
1. Console Applications
These applications contains similar user interface to the operating systems like MS-
DOS and UNIX.
Doesn‘t contain any graphical features like mouse pointer, colors, fonts, buttons etc.
Offers graphical features like mouse pointer, colors, fonts, buttons, text boxes etc.
Examples:
i. Windows Time.
iv. Database services like SQL Server, My SQL and Oracle etc.
etc.
To see the all the installed windows services on the system, click on ―Start‖ –
―Control Panel‖ – ―Administrative Tools‖ – ―Services‖.
Some other web sites are offering general purpose services that can be used by
anybody like E-Mail, Search Engines, and Blogs etc.
So, there is much demand for these applications in modern software development
industry.
In .NET Framework, the web sites can be developed using the technology called
ASP.NET.
Ex:
i. http://www.yahoo.com/
ii. http://www.google.co.in/
iii. http://www.orkut.com/
iv. http://www.hotmail.com/
The web services are used to implement ―SOA‖ (Service Oriented Architecture) in
web applications.
Examples:
i. Online shopping requires credit card authentication, from back web site.
7. WPF Applications
WPF stands for Windows Presentation Foundation.
These Applications support more advanced graphical features like shapes, object
transformation, brushes etc.
C
(For General Programming Experience)
SQL
(For writing the database queries in ADO.NET)
HTML
(For web page designing in ASP.NET)
Promises by Microsoft:
Multiple platforms: The system runs on a broad range of computers, from servers and
desktop machines, smart phones and cell phones.
Industry standards: The system uses industry standard communication protocols,
such as XML, HTTP, SOAP, and WSDL.
Security: The system can provide a much safer execution environment, which can‘t be
hacked or robbed by others.
.NET Framework 1.0 1.0.3705.0 Feb 13, 2002 Visual Studio.NET 2002
.NET Framework 1.1 1.1.4322.573 April 24, 2003 Visual Studio.NET 2003
.NET Framework 2.0 2.0.50727.42 November 17, 2005 Visual Studio 2005
.NET Framework 3.0 3.0.4506.30 November 06, 2006 [No Visual Studio]
.NET Framework 3.5 3.5.21022.8 November 19, 2007 Visual Studio 2008
.NET Framework 4.0 4.0.30319.0 April 12, 2010 Visual Studio 2010
dvantages of .NET
Supports multiple languages like VC#, VB.NET, VC++.NET, VJ#.NET etc., so that the
programmer can write the code in his/her interested language.
Offers more secured environment never before.
Offers flexible data access with ADO.NET.
Supports to develop windows services and web services, which are necessary to
handle in the live projects in the modern programming world.
Supports to develop applications for small devices like PDA‘s, smart phones, mobile
phones etc.
Offers ―Partial platform independency‖, because it supports to run the .NET
applications on Windows and LINUX platforms with Mono Tool.
Offers easier and faster UI design (with drag and drop technique), when compared with
the languages like Java.
Similarities
Sl.
.NET and Java
No
Both of these support to develop console applications, windows applications, web
1
sites, web services etc.
Both use their own intermediate language. Java calls it as ―byte code‖ and .NET
2
calls it as ―MSIL‖.
3 Both are Object oriented programming languages.
4 Both support Remoting.
5 Both support multi-threading.
6 Both support web related languages like Java Script, XML, CSS etc.
7 Both support the recent web development technology like AJAX.
Both support ―Garbage collection‖, which automatically clears the un-used
8
memory.
Both support to develop the applications for small devices like PDA‘s, mobile
9
phones, smart phones etc.
10 Both offer better security features in their own style.
Differences
Sl.
.NET Java
No
It is cost effective. Costs more than It is open source product, which can be
1
$700 (nearly Rs. 35,000) freely downloaded on the Internet.
2 It‘s a collection of multiple languages It‘s itself is a language.
It‘s partially platform independent (as
.NET applications can run on
3 It‘s fully platform independent.
Windows and LINUX operating
systems)
Offers IDE as Visual Studio by Doesn‘t offer any IDE. But other IDE‘s by
4
Microsoft. other vendors such as Eclipse etc.
Offers easiest and fastest application Requires much time for the application
5 development, which indirectly reduces development, which indirectly increases
the cost of the software. the cost of the software.
Designing the UI is very much easy UI Design requires much programmer‘s
6
with ―Drag and Drop‖ technique. effort and stress.
AJAX is implementation is much time
7 AJAX is implementation is much easy. taking process, requires much code to
write.
.NET Framework: This is the general version, required to run .NET applications on
Windows operating system.
.NET Mono Framework: This is required to run .NET applications on other operating
systems like UNIX, LINUX and Solaris etc.
.NET Compact Framework: This is required to run .NET applications on other devices
like PDA (Personal Digital Assistants), Mobile phones and Smart phones.
You can see the .NET Framework Architecture in the following diagram.
Naming Convention
System
Windows Web Drawing Linq Xml Data Threading IO Text Speech Runtime
Configuration Remoting
Forms UI Printing OleDb SqlClient
HtmlControls WebControls
The Common Language Runtime (CLR) is the agent that manages your .NET
applications at execution time. In other words, CLR is the completely responsible
component of .NET Framework that is responsible to manage the .NET applications at
run time.
In other words, The Common Language Runtime (CLR) is the virtual machine in the
.NET Framework.
It provides core services such as memory management, thread management,
exception handling, security and resource management.
A .NET application is compiled into a ―bytecode‖ format known as MSIL (Microsoft
Intermediate Language). The MSIL bytecode allows .NET applications to be portable
(at least theoretically) to other platforms because the application is compiled to native
code only during runtime.
During execution, the CLR‘s JIT (just - in - time) compiles the bytecode into the
processor‘s native code and executes the application.
In .NET, when an application is compiled, into a bytecode called MSIL. That MSIL code
is stored in an assembly. The assembly is contained in one or more PE (portable
executable) files and may end with an EXE or DLL extension.
The assembly contents are:
Byte code — The code in MSIL language.
Security Information — Information about the users / user types, who can
Private Assemblies: The private assemblies are simple types. An assembly that can
be used only within a software application is called as ―Private assembly‖. This type of
assemblies contains ―.exe‖ file extension.
Shared Assemblies: An assembly that can be used by one or more software
applications is called as ―Shared Assemblies‖. This type of assemblies contains ―.dll‖
(dynamic linking library) file extension.
Example:
To get a better idea of a MSIL file and its content, take a look at the following
example, which has two console applications. One is written in C# and the other is written in
VB.NET.
The following C# code displays the “Hello, World” message in the
console window:
using System;
using System.Collections.Generic;
using System.Linq; using
System.Text; namespace
HelloWorldCS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(―Hello, World!‖);
Console.ReadLine();
}
}
}
The following VB.NET code displays the “Hello, World” message in the
console window:
Module Module1
Sub Main()
Console.WriteLine(―Hello, World!‖)
Console.ReadLine()
End Sub
End Module
Conclusion: The Main method of the VB.NET MSIL looks very similar to that of the C#.NET‘s
MSIL program.
The important thing to note here is that regardless of the language you use to develop your .NET
applications, all .NET applications are compiled to the MSIL bytecode as this example shows.
Note: MSIL can also be called as IL (Intermediate Language) and CIL (Common Intermediate
Language).
Assembly (.exe)
MSIL Code
Just-in Time
Compiler
01010101010111010
01010101010111010
01010101010111010
01010101010111010
Operating System
3. Memory Manager
The ―Memory Manager‖ component of CLR, allocates necessary memory for the
variables and objects that are to be used by the application.
4. Garbage Collector
This component of CLR de-allocates or cleans-up the un-necessary memory of the
application, after usage automatically.
Instead, in older languages such as C/C++ this kind of component is not available so
that the programmer should free-up the memory explicitly using some code.
5. Exception Manager
An exception means ―Run time error‖.
This component redirect the processor to execute the ―catch‖ block or ―finally‖ block,
whenever an exception is occurred at run time.
We can learn how to write these catch and finally blocks in C#.NET and VB.NET
languages later.
Processor:
Minimum: P-IV
Recommended: Higher than P-IV
RAM:
Minimum: 512 MB
Recommended: 1 GB (or above)
OS:
MS Windows
(XP / 2003 / Vista / 2008 / Windows 7)
Processor:
Minimum: P-IV
Recommended: Higher than P-IV
RAM:
Minimum: 512 MB
Recommended: 1 GB (or above)
OS:
MS Windows
(XP Service Pack 3 / 2003 / Vista / 2008 / Windows 7)
Initially, the ―Visual Studio 2010‖ will be opened along with ―Start Page‖.
The start page is nothing but the welcome page, which contains
Logo: A logo of ―Microsoft Visual Studio 2010‖ on the top of the start page.
Recent Projects: List of most recently opened projects. If you click on any one,
the project will be opened immediately.
Get started / Guidance and Resources / Latest News: Headlines of visual
studio help for .NET programmers. If you click on any one head line, online help
will be opened (if Internet connection is available).
Build: Compilation of entire .NET Project (all the files will be compiled at-a-
time).
class class1
int mydatamember;
void mymethod()
Namespace: It‘s nothing but a collection of classes. It may also contain sub
namespaces. A project may require implementing at least one or more classes.
Any class can‘t be defined individually, without a namespace. In .NET, all of the
classes related one application should be defined with a user defined namespace.
namespace MyApplication
{
class class1
{
}
class class2
{
}
}
In the above screen, you can see an empty form created automatically, named as ―Form1‖.
You can observe the project directory structure according to our previous example.
Note: First, recollect the project name, project location and solution name from previous
example.
bin: This folder contains the ―EXE‖ file after compiling the project.
obj: This folder cntains the temporary files of the project, while compilation.
Properties: This folder contains necessary files that contain information about the
settings and resources related to the project.
WindowsFormsApplication1.csproj (Project File): This file contains the information
about all the files related to the project; When you double click on it, the project will be
opened in Visual Studio.
Form1.cs: This file contains the executable code of ―Form1‖.
Form1.Designer.cs: This file contains the code related to the design of Form1.
Program.cs: This file contains the code of ―Program‖ class with Main() method.
1) Menu Bar: This bar contains the available menus in Visual Studio like ―File‖, ―Edit‖,
―View‖ and ―Project‖ etc.
2) Tool Bars: There are several toolbars in Visual Studio, which contain frequently used
options in Visual Studio.
3) Tabs: Displays tabs; just click to open required tab.
4) Form designer: Used to view and edit the visual design of the form.
5) Code Window: This is where you write actual programming of your application. You
can switch to this view, by right click on the ―form designer‖ and choosing ―View Code‖
(or) by pressing F7 key on the keyboard.
File Extensions in C#
Project File Extension: ―.csproj‖ (means C Sharp Project)
Code File Extension: ―.cs‖ (means C Sharp)
Basic Terminology in C#
Statement: It‘s a line in the program.
--------------;
Keyword: It‘s a reserved word, which has some pre-defined meaning. Ex: void, class,
struct, using, while, do, for, if, else etc.
Data type: It‘s a keyword, which specifies the type of the data that you are going to
store in a variable or constant. Ex: int, float, char, string etc.
Variable: It‘s a named memory location, which contains a particular type value and
which value can be changed during the program execution.
data_type variable_name;
Constant: It‘s a fixed value, which value can‘t be changed during the program
execution. Ex: 1, 10, ‗a‘, ―abcd‖.
Operator: It‘s a symbol, which performs some operation. Ex: +, -, *, /, ++ etc.
Condition: It‘s an expression, which can have a result (True / False).
class <classname>
{
//fields
//properties
//methods
}
Object: It‘s an instance to the class. The memory will be allocated for the object only,
not for the class. It is able to access the members of the class. An object can be created
as follows:
To run the application, simply press ―F5‖ key on the keyboard. Then the application will
be executed and output will be as follows.
Main() method
1. Importing section:
This section contains importing statements that are used to import (include or link) the
.NET Framework Class Library (FCL).
This is most similar to the ―include‖ statements in ―C‖ language.
Syn:
using namespace;
Note: If the required namespace is a member of another namespace, we have specify
the parent and child namespaces separated with ―.‖ (dot).
Ex:
using System;
2. Namespace declaration:
Here, a user define namespace is to be declared.
Rule: In .NET applications, all the classes related to the project should be declared in
one namespace.
Syn:
namespace namespacename
{
}
Generally, the namespace name will be same as ―Project‖ name.
2. Class declaration:
This is to declare the startup class of the project.
In every .NET application (like Console and Windows Application), there should a startup
class. In these applications, the startup class name should be ―Program‖. You can‘t
change it.
A startup class nothing but a class, which contains Main() method.
Syn:
class classname
{
3. Main() method:
As you know already in C/C++ languages, the Main() method is the Starting Execution
Point of the application.
When the application is executed, the Main() method will be executed first.
This method contains the main logic of the application.
1) Keywords
You can observe the available keywords in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleClassDemo
{
/*Demo on Console Class*/
class Program
{
static void Main(string[] args)
{
//Output demo
System.Console.WriteLine(".NET Framework is:");
System.Console.Write("C#.NET+");
System.Console.Write("VB.NET+");
System.Console.WriteLine("ASP.NET");
//Input demo
string name;
System.Console.Write("\nEnter your name: ");
name = System.Console.ReadLine();
System.Console.Read();
}
}
}
Output:
You can observe the data types, memory size and ranges inthe following table.
Note: When we declare any variable, it should be assigned to a value before its usage.
Otherwise, it causes a compile time error.
Note: ―+‖ is known as ―concatenation‖ operator, which can concatenate two similar or
different types of values as a ―string‖.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Variables
{
class Program
{
static void Main(string[] args)
{
int n = 4561;
Console.WriteLine(n);
decimal a, b, c;
double d1, d2=45.123, d3;
Console.WriteLine("d2 value is " + d2);
string s1;
bool b1 = true;
Console.WriteLine(b1);
string Country = "India";
int States = 28;
Console.WriteLine("Our country is " + Country + ". It has " + States + " states.");
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EscapeSequenceCharacters
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is first line\nThis is second line\nThis is third line.");
Output:
8) Constants
Constants look just like variables, but concept wise, they differ from variables.
The main differences between constants and variables are:
The value of constants can‘t be changed during the program execution time.
The constants should be initialized at the time of its declaration.
To declare constants,
Syn: const datatype constantname = value;
Ex: const int x=100;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Constants
{
//An application, that calculates area of circle
class Program
{
Output:
Implicit Casting
Implicit casting is possible in the following cases.
Explicit Casting
Explicit casting should be performed in the following cases:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Casting
{
class Program
{
static void Main(string[] args)
{
Output:
System.Convert.ToSByte(value);
Converts the value into ―sbyte‖ type.
System.Convert.ToByte(value);
Converts the value into ―byte‖ type.
System.Convert.ToInt16(value);
Converts the value into ―short‖ type.
System.Convert.ToUInt16(value);
Converts the value into ―ushort‖ type.
System.Convert.ToInt32(value);
Converts the value into ―int‖ type.
System.Convert.ToInt64(value);
Converts the value into ―long‖ type.
System.Convert.ToUInt64(value);
Converts the value into ―ulong‖ type.
System.Convert.ToSingle(value);
Converts the value into ―float‖ type.
System.Convert.ToDouble(value);
Converts the value into ―double‖ type.
System.Convert.ToDecimal(value);
Converts the value into ―decimal‖ type.
System.Convert.ToChar(value);
Converts the value into ―char‖ type.
System.Convert.ToString(value);
Converts the value into ―string‖ type.
System.Convert.ToBoolean(value);
Converts the value into ―bool‖ type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConversionMethods
{
class Program
{
static void Main(string[] args)
{
Output:
IMP Note:
By default, C# recognizes all the integer constants as the type of ―int‖.
In the same way, C# recognizes all the floating point constants as the type of
―double‖.
There is no ―ToObject()‖ method to convert a value into ―object‖ data type.
namespace BoxingAndUnboxingDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10;
//boxing
Object obj;
obj = x;
Console.WriteLine(obj);
//un-boxing
x = Convert.ToInt32(obj);
Console.WriteLine(x);
Console.Read();
}
}
}
Output:
Strong Rule to follow: Multiple variables with same name within the same scope
can‘t be declared anywhere.
12) Operators
C# supports different kinds of operators.
Assignment operator
=
Arithmetical / Mathematical operators
+, -, *, /, %
Relational operators
==, !=, <, >, <=, >=
Comment operators
//xxxxxxxxxxxxxx
(or)
/* xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx*/
Concatenation Operator
+
Conditional operator
?:
if-else
if (condition)
{
----;
----;
}
else
{
----;
----;
}
else-if
if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else if (condition)
{
----;
----;
}
else
{
----;
----;
}
switch-case
switch (variable)
{
case value1: ---------; break;
case value2: ---------; break;
case value3: ---------; break;
case value4: ---------; break;
default: ---------; break;
}
break
for loop / while loop / do-while loop
{
----------;
----------;
break;
----------;
}
goto
----------;
----------;
----------;
goto labelname;
----------;
----------;
labelname:
----------;
----------;
----------;
do-while
initialization;
do
{
----------;
----------;
----------;
Increment / decrement;
} while(condition);
Note: You can also implement nested loops as you implemented in C/C++.
14) Enumerations
An enumeration is a collection of constants. That means you can create your own set of
named constants by using enumerations.
Each constant will have a name with an integer value.
Syntax for Enumeration Declaration:
public enum enumname
{
Constant1 = value1, Constant2 = value2, Constant3 = value3
}
Syntax for usage
enumname.constantname
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EnumerationDemo
{
public enum Months
{
January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7,
August = 8, September = 9, October = 10, November = 11, December = 12
}
class Program
{
Output:
15) Arrays
An array is the collection of similar type of values.
Each value in the array is to be called as an element.
The total no. of array elements is called as ―Array size‖.
Implementation of Arrays:
Single Dimensional Arrays:
Array declaration:
Single-dim
Without initialization:
array
datatype[] arrayname = new datatype[size];
With initialization:
datatype[] arrayname = {val1,val2,val3,…..};
With initialization:
datatype[,] arrayname = {{val1,val2,…}, {val1,val2,…},…};
namespace ArrayDemo
{
//Demo on Single-Dim Array.
class Program
{
static void Main(string[] args)
{
//read the no. of students
int n;
Console.Write("Enter no. of students: ");
n = Convert.ToInt32(Console.ReadLine());
//calculate results
for (int i = 0; i < n; i++)
{
Output:
namespace MultiDimArrays
{
//Demo on Multi-Dimensional Arrays
class Program
{
static void Main(string[] args)
{
//Single dimensional arrays int[] x = { 10, 20,
30, 40}; Console.WriteLine("Single dimensional
array:"); for (int i = 0; i < x.Length; i++)
Console.Write(x[i] + ", ");
//Double dimensional arrays
int[,] y = { {10, 20}, {30, 40}, {50, 60} };
Console.WriteLine("\n\nDouble dimensional array:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
Console.Write(y[i, j] + " ");
Console.WriteLine();
}
//Multi dimensional arrays
int[, ,] z = { { { 5, 10 }, { 15, 20 } }, { { 25, 30 }, { 35, 40 } }, { { 45, 50 }, { 55, 60 } } };
Console.WriteLine("\nMulti dimensional array:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
Console.Write(z[i, j, k] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
Console.Read();
}
}
}
Output:
“foreach” Loop
One of the most common usages of the ―for‖ loop is to iterate through a collection of
values (array).
C# offers a simplified and easier syntax of for loop called ―foreach loop‖, designed only
for such kind of array iterations.
Syntax:
foreach (datatype variable in arrayname)
{
-----------;
-----------;
}
In the above syntax, the loop will be executed once for each value in the array. For
every iteration, the values of the array will be assigned to the variable.
For example, you take the following for loop.
int[] nums = { 10, 20, 30};
for (int i = 0;i < nums.Length; i++)
{
Console.WriteLine(nums[i]));
}
You can re-write the above example with ―foreach‖ syntax as follows:
int[] nums = { 10, 20, 30};
foreach (int n in nums)
{
Console.WriteLine(n);
}
Note: The ―arrayname.Length‖ property gets the size of the array. We discuss about the ―Array‖
class in future.
Jagged Arrays
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JaggedArraysDemo
{
class Program
{
static void Main(string[] args)
{
int[][] a = new int[3][];
a[0] = new int[] { 1, 2 };
a[1] = new int[] { 3, 4, 5, 6, 7, 8 };
a[2] = new int[] { 9, 10, 11 };
Console.Read();
}
}
}
Output:
Now, locate the ―bin‖ folder of the required application, by using the following
commands. For example, let us imagine that there is a project named
―ConsoleApplication1‖ in ―D:‖ drive.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArgsDemo
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
Console.WriteLine(args.Length + " arguments found. Those are:");
for (int i = 0; i < args.Length; i++)
Console.WriteLine(args[i]);
}
else
Console.WriteLine("No arguments found...");
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MultipleMainMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is the Main() method in Program class.");
Console.Read();
}
}
class MySample
{
static void Main(string[] args)
{
Console.WriteLine("This is the Main() method in MySample class.");
Console.Read();
}
}
}
When this program is compiled, the compiler shows 2 compile time errors.
It‘s because, two Main() methods are found in MySample class and Program class;
So that the compiler can‘t understand which Main() method is to be used as exact
entry point.
To specify the required entry point, we have to change ―Startup Object‖ option in the
project properties.
To open the project properties, click on ―Project‖ menu – ―Properties‖.
Then the project properties will be opened. Now, observe the ―Startup Object‖ option.
The ―Startup Object‖ option contains two options.
(Not Set)
MultipleMainMethods.Program
(―MultipleMainMethods‖ is the project name).
Whenever it is set to “(Not Set)”, C# compiler automatically detects the Main()
method, where it is exists. This is the default value in the ―Startup object‖ option. But
this fails whenever multiple Main() methods are defined.
Now you have to select the required class that contains the desired Main() method as
entry point.
Property:
It‘s an extension to the field, which automatically performs the specified
code, whenever its value is changed.
Object:
It‘s an instance of the class.
It‘s required because, no memory will be allocated for the class, so that
you can‘t store any data and you can‘t call any operation.
It is similar to ―structure variables‖, which is declared for the ―structure‖.
The actual memory will be allocated for the object, which includes with
all the data members.
The object can access the members that are defined in the class.
class employee
employee id Object1
name
phone
address
salary Object2
tax
net_salary
getdetails()
displaydetails()
Object3
calculate_net_salary()
By default, the objects are isolated. That means there is no any relation
between the data stored in one object and another object.
Object1 Object2
Object3
employee id = 103
name = pqr
phone = 7839403200
address = chennai
salary = 10380
tax = 1270
net_salary = 9110
C++ (vs) C#
In C++, the class definition syntax should end with ; whereas in C#, it‘s not required.
In C++, we have private section, public section and protected section separately. But in
C#, there no such kind of sections and the access modifier should be specified for each
member of the class.
In C++, it is not possible to initialize the data members in the class definition. But
whereas in C#, it is possible.
In C++, there is provision to declare the member functions inside the class and then
write the definitions of those member functions outside of the class. But in C#, there is
no such kind of provision. The methods should be defined inside of the class definition
only.
In C++, 3 access modifiers (private, protected and public) only supported. But in C#, 5
access modifiers are supported (private, protected, public, internal, protected internal).
2) Data Abstraction
4) Polymorphism
5) Inheritance
2) Data Abstraction:
Access Modifiers:
= Accessible
Rule to follow: According to the nature of data hiding, it recommends us to define the fields as
―private members‖ and methods as ―public members‖.
So that finally the object can perform only the allowed operations (defined by the methods);
can‘t perform other operations.
4) Polymorphism:
2) Run-time Polymorphism:
The decision can be made at run time.
This can be implemented with two concepts:
i) Templates / Generics: You can pass any type of
value as an argument to a method.
ii) Interfaces: Contains method declarations only,
doesn‘t contain method definitions.
5) Inheritance:
The process of creating a new class that derives all the features of another
existing class is called as ―Inheritance‖.
In other words, we can extend the features of a class.
Inherit
class classname
{
//fields
//properties
//methods
}
Note 2: The functional modifiers are static, readonly, virtual, override. We cover about these
modifiers also in further hours.
//memory allocation
objname = new classname();
(or)
obj.field
obj.property
obj.method()
namespace OOPDemo
{
class test
{
//fields
public string str = "windows";
public int num = 90251;
//methods
public void ReverseString()
{
string r = "";
int i;
int len = str.Length;
for (i = len - 1; i >= 0; i--)
r = r + str[i];
Console.WriteLine("Reversed string is: " + r);
}
//access fields
Console.WriteLine(t.num);
Console.WriteLine(t.str);
//access methods
t.ReverseString();
t.ReverseNumber();
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataHidingDemo
{
class MyMath
{
//private fields
private int x, y;
//public methods
public void SetValues(int FirstVal, int SecondVal)
{
x = FirstVal;
y = SecondVal;
}
mm.SetValues(10, 3);
mm.Addition();
mm.Subtraction();
mm.Multiplication();
mm.Division();
Console.Read();
}
}
}
Output:
ReadOnly Fields
The ―ReadOnly‖ members are just like constants according to the objects.
The ―readonly‖ modifier can be used for fields only.
Once you initialize the value of ―ReadOnly data members‖, the object can‘t change that
value, but it can access the value.
Note: The read only field‘s values can be changed inside of the class only.
To declare the read only fields:
Syntax: access_specifier readonly data_type variable_name = value;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadOnlyDataMembersDemo
{
class Sample
{
//read only data member
public readonly string CompanyName = "Wipro";
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.WriteLine(s.CompanyName);
//s.CompanyName = "TCS"; // is not allowed bcoz it is the readonly member.
Console.Read();
}
}
}
Output:
“Ref” Parameters
The reference parameters are similar to the normal parameters.
The only difference between the normal parameters and reference parameters is: When
the value is changed in the reference parameter, would automatically affect
the actual parameter in the calling portion.
Implementation: Use ―ref‖ keyword in calling portion and also in method definition.
Rule: The actual parameter at the calling portion should be a variable and can‘t be a
constant.
This is just like ―Call by reference‖ concept in C/C++.
namespace RefParameterDemo
{
class SampleClass
{
public void FirstMethod(int x, int y)
{
x++;
y++;
}
public void SecondMethod(int x, ref int y)
{
x++;
y++;
}
}
class Program
{
static void Main(string[] args)
{
int a = 10, b = 20;
SampleClass sc = new SampleClass();
Console.WriteLine(a + ", " + b);
sc.FirstMethod(a, b);
Console.WriteLine(a + ", " + b);
sc.SecondMethod(a, ref b);
Console.WriteLine(a + ", " + b);
Console.Read();
}
}
}
Output:
“Out” Parameters
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OutParametersDemo
{
class Test
{
public string GetBigAndSmall(string s1, string s2, out string small)
{
string big;
if (s1.Length > s2.Length)
big = s1;
else
big = s2;
return (big);
}
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
string s1 = "dotnet";
string s2 = "framework";
string small; //no need of initialization
string big;
big = t.GetBigAndSmall(s1, s2, out small);
Console.WriteLine("Small string: " + small);
Console.WriteLine("Big string: " + big);
Console.Read();
}
}
}
Output:
“this” Keyword
This is similar to ―this pointer‖ in C++.
It represents current working object.
It is used to access the members of current working object.
this.field
this.property
this.method()
Current object: The object, with which object, the method is called.
“this” keyword can‘t be used in the static methods, because static methods doesn‘t have
current object.
namespace ThisKeywordDemo
{
class Sample
{
//fields
public int n = 100;
//methods
public void Increment()
{
int n = 10; //incrementation value
this.n = this.n + n;
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.WriteLine(s.n);
s.Increment();
Console.WriteLine(s.n);
Console.Read();
}
}
}
Output:
Named Parameters
This feature is introduced in C#.NET 4.0.
This is used to pass the arguments to the method, with those names.
namespace NamedParametersDemo
{
class User
{
//fields
public string FirstName;
public string LastName;
//methods
public void SetUserName(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}
Console.Read();
}
}
}
Output:
2. Static Members:
If you are using ―static‖ keyword while the declaration of a field / property or a
method, then it can be called as ―Static member‖.
The main feature of non-static member is - it will not be bounded with the any
object. It is individually accessible with the class name. In other words, the static
members are accessible directly, without even creating one object also.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticMembersDemo
{
class Student
{
//non-static data members
public string StudentName;
public string Course;
//non-static methods
public void SetStudentDetails(string StuName, string Cou)
{
StudentName = StuName;
Course = Cou;
}
//static methods
public static void DisplayCollegeDetails()
{
Console.WriteLine(CollegeName);
Console.WriteLine(CollegeAddress);
}
}
class Program
{
static void Main(string[] args)
{
//access static members
Student.DisplayCollegeDetails();
Console.Read();
}
}
}
Output:
Static Classes
A static class can be created using a keyword called ―static‖ used at the class definition.
A static class can contain only static members (static data members and static methods).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticClassesDemo
{
static class Sample
{
public static string SampleStaticMember = "This is my static data member";
public static void SampleStaticMethod()
{
Console.WriteLine("This is my static method.");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Sample.SampleStaticMember);
Sample.SampleStaticMethod();
Console.Read();
}
}
}
Rules of Constructors:
Types of Constructors:
i) Implicit constructor:
A constructor, offered by the compiler implicitly is called as "Implicit constructor".
Models of Constructors:
i) Default constructor:
It's a constructor, with no arguments.
ii) Parameterized constructor:
It's a constructor, with one or more arguments.
Constructor Implementation:
i) Default constructor:
public classname()
{
---------------;
---------------;
}
Destructor
It is also a method of a class, which is having some special features just like constructor.
But it can be called automatically by the compiler, at "object destruction time".
Object destruction time means, the time of clearing of memory i.e. allocated for the
object.
Destructor Implementation:
~classname()
{
----------;
----------;
----------;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConstructorsAndDestructorsDemo
{
class Student
{
//private fields
private int StudentID;
private string StudentName;
//public method
public void Display()
{
Console.WriteLine(StudentID + ", " + StudentName);
}
//parameterized constructor
public Student(int StudentID, string StudentName)
{
this.StudentID = StudentID;
this.StudentName = StudentName;
}
//destructor
~Student()
{
Console.WriteLine("This is destructor...");
}
}
class Program
{
static void Main(string[] args)
{
//invoke default constructor
Student s1 = new Student();
s1.Display();
Console.Read();
}
}
}
namespace ObjectInitializerDemo
{
class Department
{
//fields
public int DeptNo;
public string DeptName;
public string Location;
//methods
public void Display()
{
Console.WriteLine("Department No: " + DeptNo);
Console.WriteLine("Department Name: " + DeptName);
Console.WriteLine("Location: " + Location);
}
}
class Program
{
static void Main(string[] args)
{
Department d = new Department() { DeptNo=10, DeptName="Sales",
Location="Hyderabad" };
d.Display();
Console.Read();
}
}
}
Output:
Syntax:
static classname()
{
//some code
}
Rules:
1. Static constructors can‘t contain any access modifiers.
2. Static constructors can‘t be defined with arguments.
3. Static constructors can‘t access the non-static data members.
namespace StaticConstructorsDemo
{
class MyCollege
{
//static fields
public static string CollegeName;
public static string Address;
//static constructor
static MyCollege()
{
CollegeName = "ABC College of Technology";
Address = "Hyderabad";
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyCollege.CollegeName);
Console.WriteLine(MyCollege.Address);
Console.Read();
}
}
}
Page 111 of 553
Output:
Method Overloading
Def: Method overloading is nothing but writing multiple methods with same name and
with different arguments.
To overload methods, you should follow the below rules.
1. All of the overloaded methods name should be same.
2. Any difference between the method arguments should be maintained. The
difference may be in no. of arguments or the data types of arguments.
Finally, when you call the overloaded method, automatically compiler takes the decision
that ―which method is to be called‖, based on the arguments that you are passing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MethodOverloadingDemo
{
class OverloadTest
{
public double GetSimpleInterest(double p, double n, double r)
{
double si;
si = (p * n * r) / 100;
return (si);
}
public double GetSimpleInterest(double p, double n)
{
double si;
si = (p * n * 8.45) / 100;
return (si);
}
}
Output:
Operator Overloading
Def: Re-defining the functionality of an operator is nothing but ―Operator Overloading‖.
With the support of operator overloading, you can use any of the existing operators with
the combination of objects.
For example to add two numbers, you write like this (a and b are the variables).
a+b
But suppose you have two objects declared for ―Student‖ class. Then you can‘t write like
this:
s1 + s2
Finally, if you want to use the operator with the combination of objects, you require
―Operator Overloading‖.
To implement this feature, write the ―Operator method‖ as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OperatorOverloadingDemo
{
class PersonHeight
{
//data members
private int Feet, Inches;
//methods
public void SetHeight(int Feet, int Inches)
{
this.Feet = Feet;
this.Inches = Inches;
}
//operator method
public static PersonHeight operator - (PersonHeight p1, PersonHeight p2)
{
PersonHeight ph = new PersonHeight();
if (p1.Inches < p2.Inches)
{
p1.Feet--;
p1.Inches += 12;
}
ph.Inches = p1.Inches - p2.Inches;
ph.Feet = p1.Feet - p2.Feet;
return (ph);
}
}
Output:
Types of Generics:
Generic Classes:
The generic represents a data type, during the object‘s life time of the class.
Generic Methods:
The generic represents a data type, during the method execution.
According to generic classes, when an instance is created, the required type of values
could be stored as the data members.
According to generic methods, when you call a method, you can pass different types of
arguments to the same method, without overloading it.
Object Construction:
classname<data type> objname = new classname<data type>;
Method Calling:
methodname<data type>(value);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Page 117 of 553
namespace GenericClassesDemo
{
class Sample<T>
{
T n;
public void Set(T n)
{
this.n = n;
}
public void Print()
{
Console.WriteLine(n);
}
}
class Program
{
static void Main(string[] args)
{
Sample<int> s1 = new Sample<int>();
s1.Set(10);
s1.Print();
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericMethodsDemo
{
class Sample
{
public void ReverseAndPrint<T>(T[] arr)
{
class Program
{
static void Main(string[] args)
{
int[] intArray = { 3, 5, 7, 9, 11 };
string[] stringArray = { "first", "second", "third" };
double[] doubleArray = { 3.567, 7.891, 2.345 };
Console.Read();
}
}
}
Output:
Properties
―Properties‖ are one of the new features of C#.
It‘s taken from ―Visual Basic‖, not from C/C++.
Generally, ―Properties‖ concept not used in the classes, in some rare cases and complex /
large scale classes, those are used.
In simple, properties are extensions to ―data members‖.
As you know that a data member contains a value, a property implements additional
logic on that data member, especially when its value is changed.
For example, you imaging a windows form.
IMP Note: No memory gets allocated for the property. So that it can‘t store any value. To store
the actual value, we use a ―private data member‖.
Note: There should be some difference in the variable name and property name.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PropertyDemo
{
class Student
{
//private fields
private string studentname_val;
private int age_val;
//public properties
public string StudentName
{
set
{
if (value.Length <= 20)
{
Console.WriteLine("The student name is changed as " + value);
studentname_val = value;
}
else
{
Console.WriteLine("Why you are assigning two large name...?");
}
}
get
{
return studentname_val;
}
}
Page 122 of 553
public int Age
{
set
{
if (value>=18 && value<=60)
{
Console.WriteLine("The student age is changed as " + value);
age_val = value;
}
else
{
Console.WriteLine("Why you are assigning the wrong age...?");
}
}
get
{
return age_val;
}
}
}
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.StudentName = "Syam";
Console.WriteLine(stu.StudentName);
Console.WriteLine();
stu.Age = 25;
Console.WriteLine(stu.Age);
Console.WriteLine();
stu.StudentName = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(stu.StudentName);
Console.WriteLine();
stu.Age = 900;
Console.WriteLine(stu.Age);
Console.Read();
}
}
}
Ex:
private string name;
public string Name
{
get
{
return (name);
}
}
Ex:
private string name;
public string Name
{
set
{
name = value;
}
}
Ex:
public string Name { get; set; }
All of the examples up to now have been implemented with one or more classes within
the same file.
But in the real programming world, each class will be implemented in individual file.
To do so,
o Click on ―Project‖ menu – ―Add Class‖.
o Enter the name of the new class.
o Click on ―Add‖ button to confirm.
o Then a new file will be created in the same project named as:
classname.cs
Note: (cs stands for C Sharp)
Demo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassDefInSeperateFiles
{
class Demo
{
public void DemoMethod()
{
Console.WriteLine("This is demo method...");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Output:
Partial Classes
The ―partial‖ keyword allows you to define a class, struct or interface across multiple
files.
As you learned above, each class will be placed in individual files.
But in some situations in future, you may require to define a class within multiple files. In
other words, the class definition can be split into multiple files.
For example, if multiple programmers need to develop a class simultaneously, this may
be required. In the same way, in windows applications, the automatic code generator
generates some design part code for your own form class. In this case also, ―partial
classes‖ are required.
Implementation:
MyClassPart1.cs
partial class myclass
{
//some members
}
SampleClassPart1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
partial class SampleClass
{
public void FirstMethod()
{
Console.WriteLine("This is first method.");
}
}
}
SampleClassPart2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
partial class SampleClass
{
public void SecondMethod()
{
Console.WriteLine("This is second method.");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
partial class SampleClass
{
public void ThirdMethod()
{
Console.WriteLine("This is third method.");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialClasses
{
class Program
{
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
sc.FirstMethod();
sc.SecondMethod();
sc.ThirdMethod();
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerDemo
{
class IndexDemo
{
//array field
public string[] countries = new string[10];
//constructor
public IndexDemo()
{
for (int i = 0; i < countries.Length; i++)
countries[i] = "Not set";
}
//method
public void ShowCountries()
{
//indexer
public string this[int ind]
{
get
{
return countries[ind];
}
set
{
countries[ind] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
IndexDemo id = new IndexDemo();
id.ShowCountries();
Console.Read();
}
}
}
Output:
1) Implementation Inheritance:
2) Interface Inheritance:
1) Single Inheritance
2) Hierarchical Inheritance
An inheritance relationship,
BaseClass
with only one super class and
multiple sub classes.
DerivedClass 1 DerivedClass 2
3) Multi-Level Inheritance
4) Multiple Inheritance
An inheritance relationship,
with only multiple super classes
BaseClass 1 BaseClass 2
and only one sub class.
―Multiple Implementation
Inheritance‖ is not supported DerivedClass
by C#, but ―Multiple Interface
Inheritance‖ is supported by C#.
An inheritance relationship
that contains a
Intermediate Class 1 Intermediate Class 2
combination of any other
two types of inheritances.
Ex: DerivedClass
Multiple +
Hierarchical Inheritance
Multiple + Multi Level Inheritance etc.
Note: Other OOP languages like C++ support multiple inheritance. But C# and VB.NET doesn‘t
support multiple inheritance to avoid some practical problems while developing future GUI
applications like windows forms applications, web sites etc.
But instead, C# and VB.NET supports ―multiple interface inheritance‖, because it doesn‘t
cause any practical problems.
Invoke members
obj.SuperClassMember
obj.SubClassMember
Example
In the above example, we have two classes called ―A‖ and ―B‖. The inheritance
relationship has been established between these classes. Now, the ―A‖ class is called as
―Super‖ class and ―B‖ class is called as ―Sub‖ class. All the members of ―A‖ class are
exactly copied into ―B‖ class. Finally, whenever you construct an object for the ―B‖ class,
you can access both ―Hello()‖ method and ―Hai()‖ method also from that object. This is
what we learned up-to-now.
But sometimes, some of the super class members may not be accessible directly from
the sub class‘s object. This kind of nature depends on the ―access modifiers‖, we use in
the super class, while we declare the super class members.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleInheritanceDemo
{
//super class
class Country
{
public void ShowCountry()
{
Console.WriteLine("This is India..");
}
}
//sub class
class State : Country
{
public void ShowState()
{
Console.WriteLine("This is Andhra Pradesh..");
}
}
class Program
{
static void Main(string[] args)
{
//create instance for sub class
State st = new State();
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProtectedModifierDemo
{
//super class
class Country
{
protected void ShowCountry()
{
Console.WriteLine("This is India..");
}
}
//sub class
class State : Country
{
public void ShowState()
{
ShowCountry();
Console.WriteLine("This is Andhra Pradesh..");
}
}
class Program
{
static void Main(string[] args)
{
//create instance for sub class
State st = new State();
//access the members
st.ShowState();
Console.Read();
}
}
Output:
}
class two : one //can‘t inherit this. Will give a compilation error.
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewKeywordDemo
{
class US
{
public void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public new void ShowCountry()
{
Console.WriteLine("This is India.");
}
}
class Program
{
static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}
Output:
namespace VirtualDemo
{
class US
{
public virtual void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public override void ShowCountry()
{
Console.WriteLine("This is India.");
}
}
class Program
{
static void Main(string[] args)
{
India i = new India();
i.ShowCountry();
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BaseKeywordDemo
{
class US
{
public virtual void ShowCountry()
{
Console.WriteLine("This is United States.");
}
}
class India : US
{
public override void ShowCountry()
{
base.ShowCountry(); //call the base class method
Console.WriteLine("This is India.");
}
}
class Program
{
Output:
Abstract Methods
The abstract method is same as ―pure virtual functions‖ in C++.
The abstract method can be declared with ―abstract‖ keyword like this:
public abstract void samplemethod();
The abstract method doesn‘t contain method definition; it contains only method
declaration as above.
The abstract methods can be declared only within abstract classes.
Abstract Classes
A class that is declared with ―abstract‖ keyword is called as ―abstract class‖.
abstract class classname
{
Rule: If a class contains at least one abstract method, that class should be declared as
abstract class.
The abstract class can contain abstract methods, non-abstract class and normal data
members also.
Note: You can‘t create an object for the abstract class. It can be inherited from another
non-abstract class.
The non-abstract class, that inherits the abstract class, should implement the
definition(s) (with ―override‖ keyword) for all of the abstract methods declared in the
abstract class.
Note: The access modifiers used in the base and derived classes for the abstract
methods should be same.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractDemo
{
//abstract class
abstract class MyBaseClass
{
public abstract void FirstMethod();
public void SecondMethod()
{
Console.WriteLine("This is Non-Abstract Method");
}
}
//non-abstract class
class MyDerivedClass : MyBaseClass
{
Output:
Summary of Modifiers
Up to now, you learned several modifiers like static, new, virtual, abstract, override,
sealed.
You get a summary of all of these modifiers with following table:
Sl.
Modifier Applies to Description
No
The method hides a base class method with same
1 new Methods only
signature.
The member does not depends / instantiates with any of
2 static All members with its class‘s objects. It can be accessed with its class
name.
3 virtual Methods only The member can be overridden by a derived class.
The abstract class can‘t be instantiated.
The abstract method is nothing but a virtual method that
Classes and
4 abstract contains only declaration with no definition. It should be
Methods only
implemented with ―override‖ keyword in the derived
class.
The member overrides an inherited virtual or abstract
5 override Methods only
member of the base class.
Features of Interfaces:
o The interface can be declared with ―interface‖ keyword, as follows:
interface interfacename
{
}
o The interface contains only method declarations and can‘t contain method
definitions (similar to the abstract methods).
o The interface can‘t contain any data members but can contain ―automatic
properties‖ (Already you know that the automatic property doesn‘t contain
definitions for ―get‖ and ―set‖ accessors).
o Interface methods are by default ―public‖. You can‘t use another access modifier
like private and public etc.
o The interface can‘t be instantiated. That means you can‘t create an object for the
interface.
o The interface can‘t contain constructors.
o The class that inherits the interface is called as Implementation Class.
o The implementation class should implement the definitions for all the interface
methods. If not, it would generate compile time errors.
o One interface can be inherited by any no. of classes (Hierarchical inheritance).
o One class can inherit any no. of interfaces (Multiple inheritance).
o The interface methods can‘t be declared as ―virtual‖ or ―static‖ in the interface
definition.
namespace InterfaceDemo
{
interface SimpleInterest
{
double GetSimpleInterest(double P, int N, double R);
}
class SimpleInterestImpl : SimpleInterest
{
public double GetSimpleInterest(double P, int N, double R)
{
return ((P * N * R) / 100);
}
}
class Program
{
static void Main(string[] args)
{
SimpleInterestImpl sii = new SimpleInterestImpl();
Console.WriteLine("Simple Interest: " + sii.GetSimpleInterest(5000, 3, 4.5));
Console.Read();
}
}
}
Structures
This concept is not new in C#; it is taken from C language.
In C language‘s structures, you can write only some member variables, called as ―data
members‖ / ―fields‖. But in C#‘s structures, you can write fields along with some
methods also.
So, In C#, structures are almost all similar to the classes, but having some differences
with the classes.
Implementation:
Define structure
struct structurename
{
//fields
//methods
}
namespace StructuresDemo
{
struct Employee
{
//fields
private int EmployeeID;
private string EmployeeName;
private double Salary, Tax, NetSalary;
//methods
public void ReadData()
{
Console.Write("Enter Employee ID: ");
EmployeeID = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Employee Name: ");
EmployeeName = Console.ReadLine();
Console.Write("Enter Salary: ");
Salary = Convert.ToDouble(Console.ReadLine());
}
public void Calculate()
{
Tax = Salary * 10 / 100;
NetSalary = Salary - Tax;
}
public void DisplayData()
{
Console.WriteLine("\n\nEmployee ID: " + EmployeeID);
Console.WriteLine("Employee Name: " + EmployeeName);
Console.WriteLine("Salary: " + Salary);
Console.WriteLine("Tax: " + Tax);
Console.WriteLine("Net Salary: " + NetSalary);
}
}
class Program
{
static void Main(string[] args)
{
//create structure instance
Employee e = new Employee();
//call the methods
e.ReadData();
e.Calculate();
e.DisplayData();
Console.Read();
}
}
}
Implementation:
When you want to implement this concept practically, simply take a new static class first.
In this static class, write a static method, with the required name.
In that method, the first argument should be like this:
this classname argumentname
Here, in place of ―classname‖, specify the class name, for which you want to write the
extension method.
Then the ―argument name‖ acts as ―this‖ pointer in the code.
Note: Even though it is defined as a ―static method‖ it is accessible as a non-static
method from the object of the source class.
Syntax:
public static return_type method_name(this class_name arg, <other args if any>)
{
//some code
}
Limitation: You can‘t add a ―static method‖ for an existing class.
StringExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodsDemo
{
static class StringExtension
{
public static string Reverse(this String str)
{
char[] ch = str.ToCharArray();
Array.Reverse(ch);
string mystr = new String(ch);
return (mystr);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodsDemo
{
class Program
{
static void Main(string[] args)
{
string s = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(s.Reverse());
Console.Read();
}
}
}
Output:
Implementation Syntax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Console.Read();
}
}
}
Output:
namespace MultiCastDelegatesDemo
{
class Test
{
public void ShowSquare(int n)
{
int x = n * n;
Console.WriteLine("Square: " + x);
}
public void ShowCube(int n)
{
int x = n * n * n;
Console.WriteLine("Cube: " + x);
}
}
class Program
{
delegate void MyDelegate(int n);
static void Main(string[] args)
{
Test t = new Test();
MyDelegate md = new MyDelegate(t.ShowSquare);
md += new MyDelegate(t.ShowCube);
md.Invoke(10);
Console.Read();
}
}
}
Output:
Manipulations on Arrays
Copying arrays:
Syn: arrayname.CopyTo(DestinationArray, StartIndex);
Ex: a.CopyTo(b, 0);
Note: The size and dimensions of both a and b arrays, should be same. It copies
all the elements into the destination array.
Sorting arrays:
Syn: Array.Sort(arrayname);
Ex: Array.Sort(a);
Note: ―Sort‖ is a static method of ―Array‖ class. It sorts all the array elements in
ascending order.
Reversing arrays:
Syn: Array.Reverse(arrayname);
Ex: Array.Reverse(a);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayClassDemo
{
class Program
{
static void Main(string[] args)
{
//single dimensional array
Console.WriteLine("Single dimensional array:");
int[] a = { 643, 32948, 39, 23094, 112};
foreach (int i in a)
Console.Write(i + " ");
Console.WriteLine("\nLength: " + a.Length);
Console.WriteLine("Rank: " + a.Rank);
//string array
Console.WriteLine("\nString array:");
//copying arrays
Console.WriteLine("\n\nSingle dim array after copy:");
int[] c = new int[5];
a.CopyTo(c, 0);
foreach (int i in c)
Console.Write(i + " ");
//sorting arrays
Array.Sort(c);
Array.Sort(s);
Console.WriteLine("\n\nSingle dim array after sorting:");
foreach (int i in c)
Console.Write(i + " ");
Console.WriteLine("\n\nString array after sorting:");
foreach (string i in s)
Console.Write(i + " ");
//reversing arrays
Array.Reverse(c);
Array.Reverse(s);
Console.WriteLine("\n\nSingle dim array after reversing:");
foreach (int i in c)
Console.Write(i + " ");
Console.WriteLine("\n\nString array after reversing:");
foreach (string i in s)
Console.Write(i + " ");
Console.WriteLine("\n");
//searching an element
Console.WriteLine("Index of 'Java' in the string array is : " + Array.IndexOf(s,
"Java"));
Console.Read();
}
}
}
namespace MathClassDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Abs(-84));
Console.WriteLine(Math.Pow(10, 3));
Console.WriteLine(Math.Min(5, 100));
Console.WriteLine(Math.Max(5, 100));
Console.WriteLine(Math.Min(25, Math.Min(78, 87)));
Console.WriteLine(Math.Max(25, Math.Max(78, 87)));
Console.WriteLine(Math.Sqrt(9));
Console.WriteLine(Math.Floor(10.56));
Console.WriteLine(Math.Ceiling(10.56));
Console.WriteLine(Math.Round(10.56));
Console.WriteLine(Math.Round(10.23));
Console.WriteLine(Math.Round(10.2342, 2));
Console.WriteLine(Math.Round(10.2392, 2));
Console.WriteLine(Math.Sign(10));
Console.WriteLine(Math.Sign(-10));
Console.WriteLine(Math.PI);
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringDemo
{
class Program
{
static void Main(string[] args)
{
//create string object
string s = "I am a .NET Developer";
Console.WriteLine("The original string is: " + s);
Console.WriteLine("The original string's length is: " + s.Length);
//copy strings
string s1;
s1 = s;
Console.WriteLine("\nThe copied string is: " + s1);
//concatenate strings
string s2 = "I am working in Wipro.";
string s3;
s3 = s1 +". " + s2;
Console.WriteLine("\nThe concatenated string is: " + s3);
//compare strings
if (s1 == s2)
Console.WriteLine("\ns1 and s2 are equal");
else
Console.WriteLine("\ns1 and s2 are not equal");
string s4 = s1;
if (s1 == s4)
Console.WriteLine("\ns1 and s4 are equal");
else
Console.WriteLine("\ns1 and s4 are not equal");
//right padding
string s19 = s.PadRight(26, '*');
Console.WriteLine("\nString after right padding: " + s19);
Console.Read();
}
}
}
Object Implementation:
Create an instance for “System.DateTime” structure:
DateTime dtobj;
Assign any date&time value:
dtobj = Convert.ToDateTime(―mm/dd/yyyy hh:mi:ss AM/PM‖);
Assign System date&tme:
dtobj = DateTime.Now;
Date Comparisons
Date comparisons are very simple in C#, because ―DateTime‖ structure overloads the
necessary relational operators such as ―==‖, ―!=‖, ―<‖, ―>‖, ―<=‖, ―>=‖.
You can directly use these operators between two dates and get the appropriate result.
Date Difference
To find out the difference between two dates, simply use ―-― operator, which is already
overloaded.
When you use this, you can get the result as an ―System.TimeSpan‖ object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DateTimeDemo
{
class Program
{
static void Main(string[] args)
{
//create DateTime obj
DateTime dt1;
dt1 = Convert.ToDateTime("7/16/2009 6:23 PM");
DateTime dt2 = DateTime.Now;
//display dates
Console.WriteLine("dt1 is: " + dt1.ToString());
Console.WriteLine("dt2 is: " + dt2.ToString());
//adding values
DateTime dt3 = dt2.AddDays(5);
Console.WriteLine("\ndt2 after adding 5 days: " + dt3.ToShortDateString());
DateTime dt4 = dt2.AddMonths(5);
Console.WriteLine("\ndt2 after adding 5 months: " + dt4.ToShortDateString());
DateTime dt5 = dt2.AddYears(5);
Console.WriteLine("\ndt2 after adding 5 years: " + dt5.ToShortDateString());
DateTime dt6 = dt2.AddHours(5);
Console.WriteLine("\ndt2 after adding 5 hours: " + dt6.ToLongTimeString());
DateTime dt7 = dt2.AddMinutes(5);
Console.WriteLine("\ndt2 after adding 5 minutes: " + dt7.ToLongTimeString());
DateTime dt8 = dt2.AddSeconds(5);
Console.WriteLine("\ndt2 after adding 5 seconds: " + dt8.ToLongTimeString());
//date comparision
if (dt1 == dt2)
Console.WriteLine("\ndt1 and dt2 are equal.");
else if (dt1 > dt2)
Console.WriteLine("\ndt1 is greater than dt2.");
else if (dt1 < dt2)
Console.WriteLine("\ndt1 is less than dt2.");
Output:
Implementation:
Create an instance:
Random r = new Random();
Generate the random number based on the given boundary values:
r.Next(min value, max value);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomDemo
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
for (int i = 0; i < 300; i++)
{
Console.Write(r.Next(1, 300) + ", ");
}
Console.Read();
}
}
}
Collections
The concept of ―collections‖ is basically developed from ―Arrays‖.
Already you know that, arrays are multiple value containers of fixed type.
In order to hold different types of values on the same array, you require collections.
Another advantage of collections is those are dynamic sizable. In other words, the array
is of fixed size and the collection is of dynamic size.
Finally, if you don‘t know how many values are to be stored in the array at the time of its
declaration, you require to use ―collections‖; (or) if you want to store different type of
values in the same array, at that case also, you require to use ―collections‖.
.NET offers some pre-defined classes for maintenance of collections.
Collection Classes:
List:
1) Contains n no. of values of same type. It‘s a generic class.
2) This is member of ―System.Collections.Generic” namespace.
ArrayList:
1) Contains n no. of values of different types.
Import namespace:
using System.Collections.Generic;
Create instance:
List<data type> obj = new List<data type>();
Add values:
obj.Add(value);
Get the currently existing no. of values in the collection:
obj.Count
Get the individual element in the collection:
obj[index];
Import namespace:
using System.Collections;
Create instance:
ArrayList obj = new ArrayList();
Add values:
obj.Add(value);
Get the currently existing no. of values in the collection:
obj.Count
Get the individual element in the collection:
obj[index];
using System.Collections.Generic;
namespace ListClass
{
class Program
MyMessages.Add("Good Morning");
MyMessages.Add("Good Afternoon");
MyMessages.Add("Good Evening");
MyMessages.Add("Good Night");
//MyMessages.Add(10); //error
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ArrayListClass
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.Read();
}
}
}
Output:
Collection Initializer
As per the previous examples with collections, we require to add the values to the
collections using ―Add()‖ method.
Suppose you want to add so many elements to the collection. Then if you are using it
takes ―Add()‖ method (as above), it takes no. of lines of code.
To solve this problem, ―Collection Initializer‖ can be used.
Purpose: To initialize the elements of a collection, at the time declaration.
Syntax:
1) “List” collection class:
List<data type> obj = new List<data type>() { val1, val2, …. };
2) “ArrayList” collection class:
ArrayList obj = new ArayList() { val1, val2, …. };
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CollectionInitializerDemo
{
class Program
{
static void Main(string[] args)
{
//Collection Initializer with List class
Console.WriteLine("List:");
List<string> lst = new List<string>() { "one", "two", "three", "four" }; //collection
initializer
lst.Add("five"); //add additional elements if required
Console.WriteLine("\n\nArray List:");
ArrayList arrlst = new ArrayList() { "emp_001", "Srinivas", 8900, "Washington" };
//collection initializer
arrlst.Add(DateTime.Now); //add additional elements if required
foreach (object s in arrlst)
Console.WriteLine(s);
Console.Read();
}
}
}
Output:
Note: By default, ―System.Drawing‖ assembly will not be linked with the ―Console applications‖.
That‘s why you need to add a reference to that as follows:
Click on ―Project‖ menu – ―Add Reference‖.
Select ―System.Drawing‖ assembly.
Click on OK. Then the ―System.Drawing‖ assembly will be linked with the current
project and it will be displayed in ―References‖ folder in the Solution Explorer.
Implementation:
Import the namespace:
using System.Drawing.Printing;
Construct the object:
PrintDocument obj = new PrintDocument();
Assign the document name, that is to be printed:
obj.DocumentName = ―file path to be printed‖;
Start Printing:
obj.Print();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Printing;
namespace PrintingDemo
{
class Program
{
Output:
Library: System.IO.DriveInfo
The ―DriveInfo‖ class object can represent a drive on the computer. It offers several properties
and methods to access the related information of the drive.
Object Construction:
Syn: DriveInfo obj = new DriveInfo(―drive letter‖);
Ex: DriveInfo obj = new DriveInfo(―c‖);
You can observe the list of all available properties, methods of this class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
Page 184 of 553
namespace DriveInfoDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the drive letter (a to z):");
string driveletter = Console.ReadLine();
if (d.IsReady)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.DriveType);
Console.WriteLine(d.VolumeLabel);
Console.WriteLine(d.DriveFormat);
Console.WriteLine(d.TotalSize + " bytes.");
Console.WriteLine(d.TotalFreeSpace + " bytes.");
}
else
Console.WriteLine(d.Name + " - " + " Not Ready.");
Console.Read();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace GetDrivesDemo
{
Page 185 of 553
class Program
{
static void Main(string[] args)
{
DriveInfo[] dinfo = DriveInfo.GetDrives();
Console.WriteLine(dinfo.Length + " drives found on this computer.");
foreach (DriveInfo d in dinfo)
{
Console.WriteLine();
if (d.IsReady)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.DriveType);
Console.WriteLine(d.VolumeLabel);
Console.WriteLine(d.DriveFormat);
Console.WriteLine(d.TotalSize + " bytes.");
Console.WriteLine(d.TotalFreeSpace + " bytes.");
}
else
Console.WriteLine(d.Name + " - " + d.DriveType + " - Not Ready.");
}
Console.Read();
}
}
}
Output:
Library: System.IO.DirectoryInfo
This class object represents a folder on the file system. This able to get the information
of the folder and also to perform certain operations on that folder.
Object Construction:
Syn: DirectoryInfo obj = new DirectoryInfo(―path of the directory‖);
Ex: DirectoryInfo obj = new DirectoryInfo(―c:\\windows‖);
You can observe the list of all available properties, methods of this class.
using System.IO;
namespace DirectoryInfoDemo1
{
class Program
{
static void Main(string[] args)
{
string directorypath = "c:\\windows\\help";
DirectoryInfo dinfo = new DirectoryInfo(directorypath);
if (dinfo.Exists)
{
Console.WriteLine("Directory Name: " + dinfo.Name);
Console.WriteLine("Directory Full Path: " + dinfo.FullName);
Console.WriteLine("\nCreated on: " + dinfo.CreationTime);
Console.WriteLine("Last accessed on: " + dinfo.LastAccessTime);
Console.WriteLine("Last modified on: " + dinfo.LastWriteTime);
Console.WriteLine("\nParent: " + dinfo.Parent.FullName);
Console.WriteLine("Root: " + dinfo.Root);
Console.WriteLine("\nFiles:");
FileInfo[] fobjs = dinfo.GetFiles();
foreach (FileInfo f in fobjs)
Console.WriteLine(f.FullName);
Console.WriteLine("\nSub Directories:");
DirectoryInfo[] dobjs = dinfo.GetDirectories();
foreach (DirectoryInfo d in dobjs)
Console.WriteLine(d.FullName);
}
else
Console.WriteLine(directorypath + " is not available on the system.");
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DirectoryInfoDemo2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the directory path:");
string directorypath = Console.ReadLine();
DirectoryInfo dinfo = new DirectoryInfo(directorypath);
if (!dinfo.Exists)
{
dinfo.Create();
Console.WriteLine("Directory created.");
}
else
Console.WriteLine(directorypath + " is already exists.");
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DirectoryInfoDemo3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the directory path:");
string directorypath = Console.ReadLine();
DirectoryInfo dinfo = new DirectoryInfo(directorypath);
if (dinfo.Exists)
{
dinfo.Delete(true);
Console.WriteLine("Directory deleted.");
}
else
Console.WriteLine(directorypath + " doesn't exists.");
Console.Read();
}
}
}
Output:
Library: System.IO.FileInfo
This class object represents a file on the file system. This able to get the information of
the file and also to perform certain operations on that folder.
Object Construction:
Syn: FileInfo obj = new FileInfo(―path of the file‖);
Ex: FileInfo obj = new FileInfo(―c:\\tc\list.h‖);
You can observe the list of all available properties, methods of this class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
if (fobj.Exists)
{
Console.WriteLine("\nName: " + fobj.Name);
Console.WriteLine("Full Name: " + fobj.FullName);
Console.WriteLine("Extension: " + fobj.Extension);
Console.WriteLine("Directory: " + fobj.DirectoryName);
Console.WriteLine("File Size: " + fobj.Length + " bytes");
Console.WriteLine("Created on: " + fobj.CreationTime);
Console.WriteLine("Last Accessed on: " + fobj.LastAccessTime);
Console.WriteLine("Last Modified on: " + fobj.LastWriteTime);
}
else
Console.WriteLine("File not found.");
Console.Read();
}
}
}
File Streams
To write / read the content to / write the file, you require file streams.
A file stream acts as a pointer for the file, which contains the memory address of the file
on the disc.
There are two types of file streams.
1) Reading Streams
2) Writing Streams
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileWriteDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);
if (!fobj.Exists)
{
string content;
Console.WriteLine("\nEnter content to write:");
content = Console.ReadLine();
Console.WriteLine("\nWritten successfully!");
}
else
Console.WriteLine("File already exists.");
Output:
using System;
using System.IO;
namespace FileReadDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filepath);
string content = sr.ReadToEnd();
Console.WriteLine(content);
sr.Close();
}
else
Console.WriteLine("File not found.");
Console.Read();
}
}
}
Multi Tasking:
Def: Ability of the OS, that is able to perform more than one task, at-a-time
(simultaneously) is called as ―Multi-Tasking‖.
As a part of this, OS allocates the CPU clock (CPU capacity) for each task.
Note: Just like multi-tasking, OS allocates the CPU clock for each thread.
Threading Architecture:
.NET Application
OS
Thread 1
CLR
Thread 2
Thread 3
Processor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SimpleThreadingDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 300; i++)
Console.Write("i=" + i + " ");
}
private void SecondMethod()
{
for (int j = 1; j <= 300; j++)
Console.Write("j=" + j + " ");
}
public void Display()
{
Thread th1 = new Thread(FirstMethod);
Thread th2 = new Thread(SecondMethod);
th1.Start();
th2.Start();
Output:
The thread state specifies the current status of the thread. Sometimes, the thread
automatically switches from one state to another state automatically; at some other times, you
can switch its state by using the methods offered by ―Thread‖ class.
The following diagram called ―Thread Life Cycle‖ describes the different states of a
thread.
Ready
Start()
Running
Sleeping
Suspend()
Resume()
Suspended
Automatic / Abort()
Dead
“Thread”classmethods:
o thobj.Start()
This method starts-up the thread execution.
o Thread.Sleep(mille_sec)
This method puts the thread under ―Sleeping‖ state, up to a certain no. of mille
seconds. When the given no. of mille seconds are completed, automatically the
thread execution will be continued.
o thobj.Suspend()
This is similar to ―Sleep()‖ method, but here, no time limit will be given. That
means whenever the ―Suspend()‖ method is called, the thread will be put under
―Suspended‖ state, until the ―Resume()‖ method is called.
o thobj.Resume()
This is to continue the thread execution that is under ―Suspended‖ state. This
method won‘t work if the thread is not under ―Suspended‖ state.
o thobj.Abort()
This is close the thread execution completely, at any time. Once, if the ―Abort()‖
method is called, the thread can‘t be started or resumed. This is the end of every
thread life cycle.
namespace ThreadLifeCycleDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 50; i++)
{
Console.Write("i=" + i + " ");
Thread.Sleep(1000);
}
}
private void SecondMethod()
{
for (int j = 1; j <= 50; j++)
{
Console.Write("j=" + j + " ");
Thread.Sleep(1000);
if (j == 20)
th1.Suspend();
else if (j == 30)
th1.Resume();
}
}
Anonymous Methods
This is used to create a method, without any name.
Syntax:
delegate()
{
//some code
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace AnonymousMethodsDemo
{
class ThreadingDemo
{
public void Display(string name)
{
Thread th1 = new Thread(delegate()
{
while (true)
{
Console.WriteLine("Welcome to " + name);
Thread.Sleep(500);
}
});
th1.Start();
}
}
Console.Read();
}
}
}
Output:
Implementation:
Create the object of ―SpeechSynthesizer‖ class:
SpeechSynthesizer ss = new SpeechSynthesizer();
Set the volume (1 to 100):
ss.Volume = n;
Set the speed of speaking (-10 to +10):
ss.Rate = n;
Change the voice gender and age:
ss.SelectVoiceByHints(VoiceGender.xxxx, VoiceAge.xxxx);
Speak the text:
ss.SpeakAsync(―message‖);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;
namespace SpeechTranslationDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text to speak:");
string TextToSpeak = Console.ReadLine();
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);
ss.SpeakAsync(TextToSpeak);
Console.Read();
}
}
}
Output:
Memory Management
Every application requires some amount of memory to run.
That memory will be allocated in the primary memory (RAM).
For every variable, individual memory will be allocated.
The RAM contains two memory locations.
o Stack RAM
o Heap
Now, we need to understand, where the
application memory is getting allocated in the Stack
RAM.
The storage area in the RAM depends on the
―data type‖ that you are using for declaring the
Heap
variable in the program.
The data types are two types in C#
o Value Types
o Reference Types
2) Reference Types:
Def: Whenever a data type is designed based on a class, it can be called as
―Reference Type‖.
The following are the reference types in C#:
1) Classes
2) Interfaces
3) String, Object
Reference types support inheritance.
Object
ValueType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ObjectClassMethods
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 100;
Console.WriteLine();
if (x.Equals(y))
Console.WriteLine("x is equal to y");
else
Console.WriteLine("x is not equal to y");
string s = x.ToString();
Console.WriteLine("\nThe integer value after converting into string is: " + s);
Console.Read();
}
}
}
Output:
Object 1
Object 2
Object 3
Object 4
Note: The above functionality is in-built in ―Garbage collector‖ component. Anyhow, there is a
provision for the programmer to command the garbage collector to perform ―garbage collection‖
at run time, programmatically. Then use the following method from ―System.GC‖ class.
Syn: System.GC.Collect();
Introduction:
In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
But you can‘t write a query on the non-database data, which in the form of objects in the
application. There, you can write the queries using the new concept called ―LINQ‖.
You can write queries on arrays, objects, databases and XML using LINQ.
Note: Before writing the LINQ queries, you should import the ―System.Linq‖
namespace..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoArrayDemo
{
class Program
{
static void Main(string[] args)
{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 4, 62 };
//ling query
IEnumerable<int> result = from n in numbers where n <= 10 select n;
Console.Read();
}
}
}
Output:
In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can execute the queries on
data sets (after learning ADO.NET) also.
LINQ Syntax:
Mandatory clauses:
from clause
in clause
select clause
1. from clause: This is used to specify the iteration variable name. This acts as alias name
for the data source.
2. in clause: This is used to specify the main data source for the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required.
6. select clause: This is used to specify the object, which is required in the query results.
7. group by (optional): This is similar to ―group by‖ clause in SQL. This retrieves grouped
data, based on a column.
Note: The result of a LINQ query should be assigned into a IEnumerable<data type> type
variable. IEnumerable is an interface.
Library: System.Collections.Generic.IEnumerable
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};
Console.Read();
}
}
}
goes to
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQwithLambaExpressions
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};
Console.Read();
}
}
}
Types of Errors:
1) Compile Time Errors: The errors occurred after compiling the program, are called as
―compile time errors‖.
2) Run Time Errors: The errors occurred during the execution of the program, are called
as ―run time errors‖.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo1
{
class Program
{
static void Main(string[] args)
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
Console.Read();
}
}
}
In the above code, the highlighted line contains an error, because it is trying to access an
array element which is in out of range of the array. So, it leads to abnormal application
termination at run time.
try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}
finally
{
--------------------;
--------------------;
}
1) try block:
The try block contains the actual code, which
is to be executed. try
{
After every try block, there should catch
---------------------;
block without fail. ---------------------;
The system tries to execute the code in the ---------------------;
---------------------;
try block. }
During the execution, if any exception
occurs, then the execution control automatically goes to catch block.
At the same time, the ―try‖ block throws the exception to the catch block in the
form of an object. That object is called as ―exception object‖.
2) catch block:
This is also known as ―error handler‖.
This is followed by the try block.
The catch block will be executed if any
exception is occurred during the execution catch (Exception ex)
of try block. {
--------------------;
The catch block contains necessary code --------------------;
which displays an error message to the }
user.
This receives the exception, thrown by the try block, in the form of an object. In
the following syntax, ―ex‖ is the ―Exception object‖. The ―Exception‖ is the class
for the exception object.
Library: System.Exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo2
{
class Program
{
static void Main(string[] args)
{
try
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred.");
}
finally
{
Console.WriteLine("This is 'finally' block.");
Console.Read();
}
}
}
}
Already we have discussed that the catch block generates an error message, when an exception
occurs. That error message can be of two types.
1. User Defined Message
2. System Defined Message
Note: Based on the situation, the above specified exception classes could be used.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo3
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;
n3 = n1 / n2;
Output:
Note: If you want to handle more than one type of exception for the same try block, then you
need to write multiple catch blocks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo4
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;
n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("This is divide by zero exception.");
}
catch (OverflowException ex)
{
Console.WriteLine("This is overflow excpetion.");
}
catch (FormatException ex)
{
Console.WriteLine("This is invalid cast exception.");
}
Console.Read();
}
}
}
Output:
The“EventLog”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace EventLogDemo
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = "c:\\sample.txt";
StreamReader sr = new StreamReader(filename);
Debugging
Bug: An error.
Debugging: Removing the bugs.
.NET offers more features for debugging. To start with the .NET application debugging, you
should create the break points.
Break Points
i) Definition: A break point is a point in the program, where the application execution
control pauses until you press ―F10‖ key. In the code, that line is highlighted with red
color.
ii) Creating a break point: Just click on the left side margin of the required line.
iv) Observing the values of variables or objects: While you are executing the
application with break points, to know the current value of any variable or object,
just place the mouse pointer over it.
The ―Immediate‖ window resides at bottom side of Visual Studio IDE. It will automatically
appear at run time. If not, press ―Ctrl + Alt + I‖.
This window is used to know the current values of the required variables, objects or data
members, which is not possible to find the value by just placing the mouse pointer over
it.
Locals window
It automatically displays all the current local variables along with their values.
To open this window, while running the application, get into the Visual Studio and press
―Ctrl+D‖ and the ―L‖.
Overviewof“ClassLibrary”Project
Global Assembly Cache (GAC): All the shared assemblies should be saved in the GAC. GAC
offers the following advantages.
Unique identification of the shared assemblies.
Avoids the DLL hell (replacement of an assembly related to one application, by another
application).
Faster accessibility.
Strong Name Keys (SNK): The ―strong name key‖ is a file, which acts as a unique
identifier, for the shared assemblies, stored in the GAC. In other words, GAC recognizes the
assembly with this strong name only.
In this example,
Class Library Project: SharedAssemblyLibrary
Console Application Project: SharedAssemblyDemo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharedAssemblyLibrary
{
public class MyLibraryClass
{
public bool IsValidLogin(string Username, string Password)
{
if (Username == "system" && Password == "manager")
return true;
else
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedAssemblyLibrary;
namespace SharedAssemblyDemo
{
class Program
{
static void Main(string[] args)
{
MyLibraryClass mlc = new MyLibraryClass();
Console.Read();
}
}
}
Output: