What is C#?
C# is
intended to be a simple, modern, general-purpose, object-oriented programming
language. Its development team is led by Anders Hejlsberg. The most recent
version is C# 4.0, which was released on April 12, 2010.
C# (pronounced
"see sharp") is a multi-paradigm programming language encompassing
imperative, declarative, functional, generic, object-oriented (class-based),
and component-oriented programming disciplines. It was developed by Microsoft
within the .NET initiative and later approved as a standard by Ecma (ECMA-334)
and ISO (ISO/IEC 23270). C# is one of the programming languages designed for
the Common Language Infrastructure.
Features of C#.
Some notable
distinguishing features of C# are:
· There
are no global variables or functions. All methods and members must be declared
within classes. Static members of public classes can substitute for global
variables and functions.
·
Managed memory cannot be explicitly freed instead, it is automatically
garbage collected.
·
Garbage collection addresses the problem of memory leaks by freeing the
programmer of responsibility for releasing memory which is no longer needed.
· In
addition to the try...catch construct to handle exceptions, C# has a
try...finally construct to guarantee execution of the code in the finally
block.
·
Multiple inheritance is not supported by C#, although a class can
implement any number of interfaces.
C# and .Net Framework.
Microsoft
announced C# in July 2000, its unveiling was part of a much larger event the
announcement of the .NET Framework. The .NET Framework is, in essence, a new
development framework that provides a fresh application programming interface
(API) to the services and APIs of classic Windows operating systems (especially
the Windows 2000 family), while bringing together a number of disparate
technologies that emerged from Microsoft during the late 1990s. Among the
latter are COM+ component services, the ASP web development framework, a
commitment to XML and object-oriented design, support for new web services
protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet Information
Services.
What is CLR?
CLR (Common Language
Runtime) is the most important component of .Net Framework. It manages and
executes code written in .Net Languages, CLR activates objects and perform
security checks. The CLR allows programmers to ignore many details of the
specific CPU that will execute the program. It also provides other important
services, including the following:
·
Memory management
·
Thread management
·
Exception handling
·
Garbage collection
·
Security Central to the .NET Framework is its runtime
execution environment, known as the Common Language Runtime (CLR) or the .NET
runtime. Code running under the control of the CLR is often termed as managed
code.
What is CTS?
In .NET
Framework, the Common Type System (CTS) is a standard that specifies how
Type definitions and specific values of Types are represented in computer
memory. It is intended to allow programs written
in different programming languages to easily share information. Functions of the Common Type System:-
in different programming languages to easily share information. Functions of the Common Type System:-
· CTS
establishes a framework that helps enable cross-language integration, type
safety, and high performance code execution.
·
CTS provides an object-oriented model that supports the complete
implementation of many programming languages.
·
CTS also defines rules that languages must follow, which helps
ensure that objects written in different languages can interact with each
other.
·
Languages supported by .NET can implement all or some common data
types. Type categories the common
type system supports two general categories of types:
Value types: Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.
Reference types: Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
Value types: Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.
Reference types: Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
What is CLS?
The
Common Language Specification (CLS) is a part of the standardized specification
of the .NET Framework originally defined by Microsoft, and later standardized
by the European Computer Manufacturers Association (ECMA). A key feature
of .NET Framework is that applications written in different languages can
interoperate with one another, taking advantage of inheritance, polymorphism,
exceptions and other features. CLS provides, set of
specification to be adhered by new language writer/compiler writer for .Net
Framework to ensure interoperability. because .net supports many languages.For
example Asp.Net application written in C#.Net language. Now we can refer any
other DLL which has been written in any other language supported by .Net Frame
Work.
Net
Frameworks Architecture
.Net is not an Operating System. It is a IDE. It provides some functionality for the programmers to build their solution in the most constructive and intellegent way ever. Just to tell you the truth, most of the codes in .Net environment resembles with the JAVA coding as if some people coming from Java would find it as to their native language.
.NET is a Framework that loads into your operating system, which you need not to load in the later versions of windows like Windows 2003 server or Just a new release of Windows Vista. As it is going to be added as a component in the next generation of windows.
Now, What is the .Net all about? Well, Its a framework that supports Common Language Runtime (CLR). As the name suggests, Common Language Runtime will be something that will run a native code for all the programming languages provided within the Architecture.
Another feature of .net is language independence, to tell you about language Independence, .Net is not at all efficient in that. Just Microsoft built their own version of languages like C++, J# (for Java), C#, VB etc that can communicate between each other. After all J#, even if they resembles with JAVA is not purely Java.. Thus, the word may look to you somewhat fake. Now what is the most prospective part of .NET? Now, with the growing Internet, ASP. NET may be the most important part of .NET technology. Well, ASP. NET has a new technology where the controls reside server side. You don't bother to use traditional client side controls. In .NET technology as there is a provision of runtime building of machine codes, a web server can directly compile and transmit codes to the browser during runtime. This is , I think the most approved and widely accepted part of .NET.
NEW things of .NET? well, during the last two years , Microsoft is constantly changing the .NET technology, that may not be good for a settled programmer. Well, first of all, in .NET 2003 Microsoft changed some features and also adds some new things. Well, new things are good, but changing the existing in such a quick succession is not at all good from programmers point of view. Again, in 2005, Microsoft publishes the new release of VISUAL STUDIO.NET 8 . This is a completely new environment. It have new releases of controls, the IDE is also different. That's not what we all wanted as a programmer. What do you say?
Now, Microsoft is also increasing its scope.. One of the most important feature that is just now introduced is AJAX. Well, the name is what can be said as Asynchronous Java Script with XML.
C# DataTypes
Data Types means what type of data a variable can hold . C# is a strongly typed language, therefore every variable and object must have a declared type. The C# type system contains three Type categories.
Value Types
Reference Types
Pointer Types
In C# it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing .
Data Types means what type of data a variable can hold . C# is a strongly typed language, therefore every variable and object must have a declared type. The C# type system contains three Type categories.
Value Types
Reference Types
Pointer Types
In C# it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing .
Ex.
int month;
int : is the data type
month: is the variable name
int : is the data type
month: is the variable name
int
int can store signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647
C# Runtime type : System.Int32
C# declaration : int month;
C# Initialization : month = 10;
C# default initialization value : 0
int can store signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647
C# Runtime type : System.Int32
C# declaration : int month;
C# Initialization : month = 10;
C# default initialization value : 0
decimal
Decimal is of a 128-bit data type.The approximate range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028
C# Runtime type : System.Decimal
C# declaration : decimal val;
C# Initialization : val = 0.12;
C# default initialization value : 0.0M
Decimal is of a 128-bit data type.The approximate range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028
C# Runtime type : System.Decimal
C# declaration : decimal val;
C# Initialization : val = 0.12;
C# default initialization value : 0.0M
string
Represents a string of Unicode characters. string variables are stored any number of alphabetic,numerical, and special characters .
C# Runtime type : System.String
C# declaration : string str;
C# Initialization : str = ".Net Environment";
Represents a string of Unicode characters. string variables are stored any number of alphabetic,numerical, and special characters .
C# Runtime type : System.String
C# declaration : string str;
C# Initialization : str = ".Net Environment";
bool
Bool is used to declare variables to store the Boolean values, true and false. In C# , there is no conversion between the bool type and other types.
C# Runtime type : System.Boolean
C# declaration : bool flag;
C# Initialization : flag = true;
C# default initialization value : false
Bool is used to declare variables to store the Boolean values, true and false. In C# , there is no conversion between the bool type and other types.
C# Runtime type : System.Boolean
C# declaration : bool flag;
C# Initialization : flag = true;
C# default initialization value : false
The following list shows the list of data types available in C# and their
corresponding class/struct in .NET class library.
|
C# Data type
|
Mapped to .NET class/struct
|
|
sbyte
|
System.SByte
|
|
byte
|
System.Byte
|
|
char
|
System.Char
|
|
float
|
System.Single
|
|
decimal
|
System.Decimal
|
|
double
|
System.Double
|
|
ushort
|
System.UInt16
|
|
short
|
System.Int16
|
|
uint
|
System.UInt32
|
|
int
|
System.Int32
|
|
ulong
|
System.UInt64
|
|
long
|
System.Int64
|
|
bool
|
System.Boolean
|
|
string
|
System.String
|
|
object
|
System.Object
|
Boxing:
Converting value types to reference types is also known as boxing. As can be seen in the example below, it is not necessary to tell the
compiler an Int32 is boxed to an object, because it takes care of this itself.
Converting value types to reference types is also known as boxing. As can be seen in the example below, it is not necessary to tell the
compiler an Int32 is boxed to an object, because it takes care of this itself.
e.g.- Int32 a = 10;
object count = a ; // Implicit boxing
Console.WriteLine("The Object count = {0}",count); // prints out 10
//However, an Int32 can always be explicitly boxed like this:
Int32 a = 10;
object count = (object) a; // Explicit boxing
Console.WriteLine("The object count = {0}",count); // prints out 10
object count = a ; // Implicit boxing
Console.WriteLine("The Object count = {0}",count); // prints out 10
//However, an Int32 can always be explicitly boxed like this:
Int32 a = 10;
object count = (object) a; // Explicit boxing
Console.WriteLine("The object count = {0}",count); // prints out 10
Unboxing: The following example intends to show how to
unbox a reference type back to a value type. First an Int32 is boxed to an
object, and then it is
unboxed again. Note that unboxing requires explicit cast.
unboxed again. Note that unboxing requires explicit cast.
Ex. Int32 a = 5;
object count = a; // Implicit
Boxing a = (int)count; // Explicit Unboxing
object count = a; // Implicit
Boxing a = (int)count; // Explicit Unboxing
Type Conversions Conversion is based on type
compatibility and data compatibility.
1. Implicit Conversion
2. Explicit Conversion
Implicit Conversion In implicit conversion the compiler will make conversion for us without asking.
char -> int -> float is an example of data compatibility.
1. Implicit Conversion
2. Explicit Conversion
Implicit Conversion In implicit conversion the compiler will make conversion for us without asking.
char -> int -> float is an example of data compatibility.
|
using System;
class Program
{
static void Main(string[] args)
{
int x =10000;
int y =20000;
long total;
// In this the int
values are implicitly converted to long data type;
//you need not to tell
compiler to do the conversion, it automatically does.
total = x + y;
Console.WriteLine("Total
is : " + total);
Console.ReadLine();
}
}
|
Explicit Conversion
In explicit conversion we specifically ask the compiler to convert the value into another data type. CLR checks for data compatibility at runtime.
In explicit conversion we specifically ask the compiler to convert the value into another data type. CLR checks for data compatibility at runtime.
|
using System;
class Program
{
static void Main(string[] args)
{
int x = 65;
char value;
value = (char)x;
// In this the int
values are explicitly converted to char data type;
//you have to tell compiler to do the conversion, it uses
casting.
Console.WriteLine("Value is: " + value);
Console.ReadLine();
}
}
|
Microsoft .NET provides three ways of type conversion:
1. Parsing
2. Convert Class
3. Explicit Cast Operator ()
Parsing
Parsing is used to convert string type data to primitive value type. For this we use parse methods with value types.
Parsing is used to convert string type data to primitive value type. For this we use parse methods with value types.
|
using System;
class Program
{
static void Main(string[] args)
{
//using parsing
int number;
float weight;
Console.Write("Enter any number : ");
number = int.Parse(Console.ReadLine());
Console.Write("Enter your weight : ");
weight = float.Parse(Console.ReadLine());
Console.WriteLine("You have entered : " + number);
Console.WriteLine("You weight is : " + weight);
Console.ReadLine();
}
}
|
Convert Class
Convert class contains different static methods like ToInt32(), ToInt16(), ToString(), ToDateTime() etc used in type conversion.
Convert class contains different static methods like ToInt32(), ToInt16(), ToString(), ToDateTime() etc used in type conversion.
|
using System;
class Program
{
static void Main(string[] args)
{
// example of using
convert class
string num = "23";
int number = Convert.ToInt32(num);
int age = 24;
string vote = Convert.ToString(age);
Console.WriteLine("Your number is : " + number);
Console.WriteLine("Your voting age is : " + age);
Console.ReadLine();
}
}
|
Explicit Cast Operator ()
It can used with any type having type compatibility and data type compatibility.
|
using System;
class Program
{
static void Main(string[] args)
{
int num1, num2;
float avg;
num1 = 10;
num2 = 21;
avg = (float)(num1 + num2) / 2;
Console.WriteLine("average is : " + avg);
Console.ReadLine();
}
}
|
C# is directly related to C and C++, C++ is a superset of C. C and C++ shares several syntax, library and functionality. In addition structures, unions, arrays, strings and pointers are most important and similar functionality for both languages.
C# inherits most of its operators, keywords, and statements directly from C++. Enums are clearly a meaningful concept in C++.
Finally I can clearly say that C# is the first component-oriented language in the C/C++ family.
C# constructors are verisimilar with C++ constructors. Like C++, methods are non-virtual by default, but can be marked as virtual.
There is also some difference between C# and C++, C# supports multiple inheritance of interfaces, but not of classes. Another difference is destructors, their syntax is same with C++ but actually they are very different.
Difference between C# and VB
C# allows 'unsafe' code, or pointer manipulation. VB allows methods with optional parameters.
C# allows assignments embedded in expressions (e.g., if ((x = y.Value) == 2)).VB allows types within interfaces.
C# has anonymous methods.VB has the very flexible Select construct (much more flexible than the C# switch).
C# has the useful conditional ternary operator (?:). The VB If function is not a good substitute since the arguments must all be evaluated. VB has the When filter for catch block headers (no equivalent exists in C#).
Difference between C# and Java
Features of C# not present in Java
C# provides integration with COM.
C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods.
C# has the ability to alias namespaces.
C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
C# implements properties as part of the language syntax.
C# allows switch statements to operate on strings.
Namespace in C#.
Namespaces group related classes and types, and they define categories in which we can include any new class that provides related functionality.
Namespaces group related classes and types, and they define categories in which we can include any new class that provides related functionality.
|
namespace MyCompany.r4r
{
class MyClass
{
// some code here
}
}
namespace MyCompany.r4r
{
class MyClass1
{
// some code here
}
}
|
Classes and Object in C#.
· Defining
Classes:- To define a new type or class, first declare it, and
then define its methods and fields. Declare a class using the class
keyword. The complete syntax is as follows:
[attributes] [access-modifiers] class identifier [:base-class]
{
class-body
}
{
class-body
}
For Example.
|
public class Test
{
public static int Main( )
{
Console.Writeline("This
is Class");
}
}
|
Defining Object:-
·
A distinction is drawn between value types and reference types. The
primitive C# types (int, char, etc.) are value types, and are created on
the stack. Objects, however, are reference types, and are created on the heap, using the keyword new, as in the following:
the stack. Objects, however, are reference types, and are created on the heap, using the keyword new, as in the following:
|
Test t = new Test();
|
t does not actually contain the value for the test class object; it contains the address of that (unnamed) object that is created on the heap. t itself is just a reference to that object.
How to create a program
in C#?
Step 1: Start notepad from Start -> Program Files
-> Accessories -> Notepad so that you can write the HelloWorld program.
The program you write in C# is also called as source code.
Step 2: Write the HelloWorld program, you can either
type the program shown below into notepad or just copy-paste it from here-
|
public class Helloworld
{
public static void Main()
{
System.Console.WriteLine("you are welcome in world of C#");
}
}
|
Step 3: Once you have finished typing your program you should Save the source code file. In fact after making any changes to your source code, you should always save the file. To save the file for the first time in notepad click on File menu -> Save As. In the Save As dialog select the directory from the Save In dropdown where you want to save your files, I generally save my files to C:\csharp, and then in the File name textbox, enter the file name as HelloWorld.cs (although you can provide any name you want but it should have an extension.cs). and click Save. Once you have saved the
source code, and if you make any further modifications, in notepad use the Ctrl+S keyboard short-cut to save your source code file.
Step 4: Since you have finished writing the source
code its time to compile it. Since we are using a command-line compiler that
ships with the .NET SDK, start the command prompt from Start -> Program
Files -> Accessories -> Command Prompt. Or go to Start -> Run, type
cmd and press enter. Now from the command prompt navigate to the directory
where you have stored the source code file by issuing the following DOS
commands.cd\ -To navigate to the root of the derived csharp - To navigate to
the csharp directory. Once you are in the csharp directory where you
saved the source code file earlier, its time to run the C# Compiler csc.exe. Issue the following command to compile our HelloWorld.cs
program:csc HelloWorld.cs
saved the source code file earlier, its time to run the C# Compiler csc.exe. Issue the following command to compile our HelloWorld.cs
program:csc HelloWorld.cs
Step 5: If the compilation of the source code was
successful then a new executable (Exe) file by the name HelloWorld.exe will be
created in the directory you compiled the source code. To execute the program
simply type the name of the executable file at the command prompt.
Points to Remember
·
C# code can be written in any text editor like notepad.
·
C# Source Code files are saved with the extension.cs.
·
C# is a case-sensitive language so you have to be careful while
typing.
·
C# runs on the .NET Platform, hence you need to install the .NET
SDK in order to compile C# programs.
· The C# compiler is
contained within the file csc.exe, which generally
resides in the C:\windows\Microsoft. NET\Framework\v1.0.4322 directory.
resides in the C:\windows\Microsoft. NET\Framework\v1.0.4322 directory.
Operators, types and
variables in C#:-
Variables- A
variable is a storage location with a type. Variables can have values assigned
to them, and those values can be changed programmatically.
A constant is a variable whose value cannot be changed.
A constant is a variable whose value cannot be changed.
Types- Like C++ and Java, C# divides
types into two sets: intrinsic Built-in types that the language offers and
user-defined types that the programmer defines. C# also divides the set of
types into two other categories: value types and reference types. The principal
difference between value and reference types is the manner in which their
values are stored in memory. C# is a "Strongly Typed" language. Thus
all operations on variables are performed with consideration of what the
variable's "Type" is. There are rules that define what operations are
legal in order to maintain the integrity of the data you put in a variable.
The Boolean Type
Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords.
Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords.
|
using System;
class Booleans
{
public static void Main()
{
bool content = true;
bool noContent = false;
Console.WriteLine("{0} C# programming language content.", content);
Console.WriteLine("This is second statement {0}.", noContent);
}
}
|
Integral Types
In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard.
In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard.
Floating Point and
Decimal Types
A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values.
A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values.
The string Type
A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console.
A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console.
The Array Type
Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.
Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.
|
using System;
class NewArray
{
public static void Main()
{
int[] myInts = { 5, 10, 15 };
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];
myBools[1] = new bool[1];
double[,] myDoubles = new double[2, 2];
string[] myStrings = new string[3];
Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]);
myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
myDoubles[0, 0] = 4.245;
myDoubles[0, 1] = 6.355;
myDoubles[1, 1] = 8.415;
myDoubles[1, 0] = 56.1148917;
Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);
myStrings[0] = "An";
myStrings[1] = "App";
myStrings[2] = "Cattt";
Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]:
{2}", myStrings[0],
myStrings[1], myStrings[2]);
}
}
|
The if Statement
if statement is used to take different paths of logic, depending on the conditions.
if statement is used to take different paths of logic, depending on the conditions.
|
using System;
using System.Windows.Forms;
class iftest
{
public static void Main()
{
if (totalMarks >= 80)
{
MessageBox.Show("Got Higher First Class ");
}
else if (totalMarks >= 60)
{
MessageBox.Show("Got First Class ");
}
else if (totalMarks >= 40)
{
MessageBox.Show("Just pass only");
}
else
{
MessageBox.Show("Failed");
}
}
}
|
The switch Statement
Another form of selection statement is the switch statement, which executes a set of logic depending on the value of a given parameter. The types of the values a switch statement operates on can be booleans, enums, integral types, and strings.
Another form of selection statement is the switch statement, which executes a set of logic depending on the value of a given parameter. The types of the values a switch statement operates on can be booleans, enums, integral types, and strings.
|
using System;
class SwitchTest
{
public static void Main()
{
Console.WriteLine("milk
bottel size: 1=Small 2=Medium 3=Large");
Console.Write("Please enter
your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int price = 0;
switch(n)
{
case 1:
price += 25;
break;
case 2:
price += 25;
goto case 1;
case 3:
price += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2,
or 3.");
break;
}
if (price != 0)
Console.WriteLine("Please insert {0} cents.", price);
Console.WriteLine("Thank you for your business.");
}
}
|
The while Loop
While loop is used to check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Syntax:-
While loop is used to check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Syntax:-
while
(<boolean expression>)
{
<statements>
}
When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code.
{
<statements>
}
When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code.
|
using System;
class whiletest
{
static void Main()
{
//
// Continue in while
loop until index is equal to ten.
//
int i = 0;
while (i < 10)
{
Console.Write("While statement ");
//
// Write the index to
the screen.
//
Console.WriteLine(i);
//
// Iterate the
variable.
//
i++;
}
}
}
|
The do Loop
A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time.
A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time.
|
using System;
class DoWhileLoopDemo
{
public static void Main()
{
int i = 0; // Initialize counter variable
do
{
if ((i % 2) == 0)
{
Console.WriteLine(i);
}
i++; //Increment the counter
}
while (i <= Limit); // Condition check
}
}
|
The for Loop
It works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (<initializer list>; <boolean expression>; <iterator list>) { <statements> }.
It works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (<initializer list>; <boolean expression>; <iterator list>) { <statements> }.
|
using System;
class ForLoop
{
public static void Main()
{
for (int i=0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;
Console.Write("{0} ", i);
}
Console.WriteLine();
}
}
|
Foreach Statement:
The foreach statement is new to the C family of languages; it is used for looping through the elements of an array or a collection.
The foreach statement is new to the C family of languages; it is used for looping through the elements of an array or a collection.
|
class ForEachTest
{
static void Main(string[] args)
{
int[] num = new int[] { 0, 1, 2, 3, 4, 5, 6,7,8 };
foreach (int i in num)
{
System.Console.WriteLine(i);
}
}
}
|
Array:
An array is the collection of similar type of objects. Array in C# is different
for the array of C++ and other languages because they are
objects. This provides them useful methods and property. Arrays allow a group of elements of a particular type to be stored
in a contiguous block of memory. Array types derive from System.Array and are declared in C# using brackets ([]).
Syntax- datatype [] array-name;
e.g.- int [] age;
The square brackets ([]) tell the C# compiler that you are declaring an array, and the type specifies the type of the elements it will
contain. In the previous example, age is an array of integers. Instantiate an array using the new keyword. For example:
age = new int[5]; This declaration sets aside memory for an array holding five integers.
objects. This provides them useful methods and property. Arrays allow a group of elements of a particular type to be stored
in a contiguous block of memory. Array types derive from System.Array and are declared in C# using brackets ([]).
Syntax- datatype [] array-name;
e.g.- int [] age;
The square brackets ([]) tell the C# compiler that you are declaring an array, and the type specifies the type of the elements it will
contain. In the previous example, age is an array of integers. Instantiate an array using the new keyword. For example:
age = new int[5]; This declaration sets aside memory for an array holding five integers.
Multidimensional Array:
Multidimensional Arrays of two types Rectangular Array and Jagged Array Rectangular Array represents n-dimensional blocks.
e.g.- int [ , ,] age = new int[17,20,34];
Jagged Arrays are arrays of arrays.
Multidimensional Arrays of two types Rectangular Array and Jagged Array Rectangular Array represents n-dimensional blocks.
e.g.- int [ , ,] age = new int[17,20,34];
Jagged Arrays are arrays of arrays.
|
int [][][] books = new int [3][][];
for (int i = 0; i < 3; i++)
{
books[i] = new int [4][];
for (int j = 0; j < 4; j++)
books[i][j] = new int [5];
}
// assign an element
books1 [1,1,1] = books [1][1][1] = 7;
|
Indexer: Indexers are usually known as smart array in
C#.It is used for treating object as an array.Defining an indexer in C#
is much like same as
defining properties. Or we can say that an indexer is a member that enables an object to be indexed in the same way as an array.
defining properties. Or we can say that an indexer is a member that enables an object to be indexed in the same way as an array.
Syntax-
<access modifier> <return type> this [argument list]
{
get
{
// Write here some code for Get
}
set
{
// Write here some code for Get
}
}
<access modifier> <return type> this [argument list]
{
get
{
// Write here some code for Get
}
set
{
// Write here some code for Get
}
}
Collections: Collections are the enumerable data structure
in C# that can be assessed using indexes or keys. Types of collections in C#
are given below-
System.Collections namespace
This provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. The interfaces
that are defined in this namespace include:
System.Collections namespace
This provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. The interfaces
that are defined in this namespace include:
·
IEnumerable
·
IEnumerator
·
ICollection
·
IList
·
IDictionary
System.Collections.Stack
System.Collections.Queue Both are derived from ICollection Interface.
The collections that inherit the IDictionary interface include:
System.Collections.SortedList System.Collections.Hashtable
The IList interface represents collections that only have value. The following are the classes that extend this interface.
System.Array
System.Collections.Stack
System.Collections.Queue Both are derived from ICollection Interface.
The collections that inherit the IDictionary interface include:
System.Collections.SortedList System.Collections.Hashtable
The IList interface represents collections that only have value. The following are the classes that extend this interface.
System.Array
·
System.Collections.ArrayList
·
System.Collections.Specialized.StringCollection
Concrete Collection Classes:
ArrayList class- This works by maintaining an internal array
of objects that is replaced with a larger array when it reaches its capacity of
elements.
BitArray class- It is a dynamically sized array of Boolean values. It is more memory-efficient than a simple array of bools because it uses only one bit for each value.
Hashtable class- A Hashtable is a standard dictionary (key/value) data structure that uses a hashing algorithm to store and index values efficiently.
Queue class- A Queue is a standard first-in, first-out (FIFO) data structure, providing simple operations to enqueue, dequeue, peek, etc.
SortedList class-A SortedList is a standard dictionary data structure that uses a binary-chop search to index efficiently.
Stack class- A Stack is a standard last-in first-out (LIFO) data structure.
StringCollection class- A StringCollection is a standard collection data structure for storing strings.
BitArray class- It is a dynamically sized array of Boolean values. It is more memory-efficient than a simple array of bools because it uses only one bit for each value.
Hashtable class- A Hashtable is a standard dictionary (key/value) data structure that uses a hashing algorithm to store and index values efficiently.
Queue class- A Queue is a standard first-in, first-out (FIFO) data structure, providing simple operations to enqueue, dequeue, peek, etc.
SortedList class-A SortedList is a standard dictionary data structure that uses a binary-chop search to index efficiently.
Stack class- A Stack is a standard last-in first-out (LIFO) data structure.
StringCollection class- A StringCollection is a standard collection data structure for storing strings.
Inheritance:
In C#, the
specialization relationship is generally implemented by using inheritance.
Inheritance is also provides the reusability, or we can say that extracts
some features from one class to another class.
|
class Bird
{
public Bird()
{
Console.WriteLine("Bird constructor");
}
public void Greet()
{
Console.WriteLine("Bird says Hello");
}
public void Talk()
{
Console.WriteLine("Bird talk");
}
public virtual void Sing()
{
Console.WriteLine("Bird song");
}
}
class Peacock : Bird
{
public Peacock()
{
Console.WriteLine("Peacock constructor");
}
public new void Talk()
{
Console.WriteLine("Peacock talk");
}
public override void Sing()
{
Console.WriteLine("Peacock song");
}
}
Bird a1 = new Bird();
a1.Talk();
a1.Sing();
a1.Greet();
Bird a2 = new Peacock();
a2.Talk();
a2.Sing();
a2.Greet();
|
Types of Inheritance:
In Object Oriented Programming concept there are
3 types of inheritances.
1. Single Inheritance,
2. Multiple Inheritance
3. Multilevel Inheritance
Single Inheritance:
public class A
{
}
public class B:A
{
}
Multiple Inheritance:
public class A
{
}
public class B
{
}
public class C:A,B
{
}
Multilevel Inheritance:
public class A
{
}
public class B:A
{
}
public class C:B
{
}
In the above three types C# don't proved Multiple Inheritance. As there is conflict of multiple override methods in base classes (say A, B in above example) As in Place C# give another feature called Interfaces using interfaces you can achieve multiple Inheritance feature.
1. Single Inheritance,
2. Multiple Inheritance
3. Multilevel Inheritance
Single Inheritance:
public class A
{
}
public class B:A
{
}
Multiple Inheritance:
public class A
{
}
public class B
{
}
public class C:A,B
{
}
Multilevel Inheritance:
public class A
{
}
public class B:A
{
}
public class C:B
{
}
In the above three types C# don't proved Multiple Inheritance. As there is conflict of multiple override methods in base classes (say A, B in above example) As in Place C# give another feature called Interfaces using interfaces you can achieve multiple Inheritance feature.
Polymorphism
Poly means many and
morph means form. Thus, polymorphism refers to being able to use many forms of
a type without regard to the details.
Creating Polymorphic Types:
For creating polymorphism there are two steps-
1. Create a base class with virtual methods.
2. Create derived classes that override the behavior of the base class’s virtual methods.
For creating polymorphism there are two steps-
1. Create a base class with virtual methods.
2. Create derived classes that override the behavior of the base class’s virtual methods.
To create a
method in a base class that supports polymorphism, mark the method as virtual.
Example.
|
public class BaseClass
{
public virtual void DoWork()
{
}
public virtual int WorkProperty
{
get {
return 0;
}
}
}
public class DerivedClass : BaseClass
{
public override void DoWork()
{
}
public override int WorkProperty()
{
get {
return 0;
}
}
}
|
Properties
In C#, properties are
natural extension of data fields. But C# provides a built in mechanism called
properties. Usually inside a class, we declare a data field as private and will
provide a set of public. In C#, properties are defined using the property
declaration syntax. The general form of declaring a property is as follows.
<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}
<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}
SET and GET methods to
access the data fields, since the data fields are not directly accessible out
side the class. We must use the set/get methods to access the data fields.
Example:
|
using System;
class Myproperty
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class Myprop
{
public static void Main()
{
Myproperty mc = new Myproperty();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}
|
Properties and
Inheritance
The properties of a
Base class can be inherited to a Derived class.
|
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'
}
}
|
Properties &
Polymorphism
A Base class property can be polymorphic overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.
A Base class property can be polymorphic overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.
|
using System;
class Base
{
public virtual int X
{
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
It is declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set assessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
It is declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set assessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
|
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'
}
}
|
Attributes
Attributes contains a powerful method of associating declarative information with C# code for types, methods, properties. Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
Attributes contains a powerful method of associating declarative information with C# code for types, methods, properties. Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
Uses of Attributes:
* Associating help documentation with program entities (through a Help attribute).
* Associating value editors to a specific type in a GUI framework (through a Value Editor attribute).
* Associating help documentation with program entities (through a Help attribute).
* Associating value editors to a specific type in a GUI framework (through a Value Editor attribute).
|
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic // Topic is a named parameter
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url is a positional parameter
{
this.Url = url;
}
private string topic;
}
|
When do we need
attributes ?
1.The System.ObsoleteAttribute
attribute that we have just described is a good example of how an attribute is
used by the compiler, certain standard attributes which are only destined for
the compiler are not stored in the assembly.
2.An attribute can be consumed by the CLR during execution. For example the .NET Framework offers the System.ThreadStaticAttribute attribute. When a static field is marked with this attribute the CLR makes sure that during the execution, there is only one version of this field per thread.
3.An attribute can be consumed by a debugger during execution. Hence, the System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the display of an element of the code the state of an object for example) during debugging.
2.An attribute can be consumed by the CLR during execution. For example the .NET Framework offers the System.ThreadStaticAttribute attribute. When a static field is marked with this attribute the CLR makes sure that during the execution, there is only one version of this field per thread.
3.An attribute can be consumed by a debugger during execution. Hence, the System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the display of an element of the code the state of an object for example) during debugging.
Structs
Structure is the
collection of dissimilar data types. A struct is a simple user-defined type, a
lightweight alternative to classes. Structs are somewhat more efficient
in their use of memory in arrays. The C# struct is a lightweight alternative to
a class. It can do almost the same as a class, but it's less
"expensive" to use a struct rather than a class.
|
class Program
{
static void Main(string[] args)
{
Home home;
Home = new Home("Blue");
Console.WriteLine(Home.Describe());
Home = new Home("Red");
Console.WriteLine(Home.Describe());
Console.ReadKey();
}
}
struct Home
{
private string color;
public Home(string color)
{
this.color = color;
}
public string Describe()
{
return "This Home is " + Color;
}
public string Color
{
get { return color; }
set { color = value; }
}
}
|
A struct is a value type and a class is a reference type.
When a struct is created, the variable to which the struct is assigned holds the struct's actual data. and When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory.
When the struct is assigned to a new variable, it is copied and When the object reference is assigned to a new variable.
The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. the new variable refers to the original object.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created.
Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
When a struct is created, the variable to which the struct is assigned holds the struct's actual data. and When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory.
When the struct is assigned to a new variable, it is copied and When the object reference is assigned to a new variable.
The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. the new variable refers to the original object.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created.
Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
When to Use Structures?
• If the instances are relatively small
• If the instance life-time is going to be very short
• If you are going to embed the instance into some other instances
• If the instances are relatively small
• If the instance life-time is going to be very short
• If you are going to embed the instance into some other instances
Delegate
A delegate
in C# language allows us to reference a method. If we are using a C or
C++ then we would sound familiar because a delegate because it
is basically a function pointer. Delegates have other uses in addition to event handling. Delegate maintains three important pieces of information :
1. The name of the method on which it make calls.
2. Any argument (if any) of this method.
3. The return value (if any) of this method.
is basically a function pointer. Delegates have other uses in addition to event handling. Delegate maintains three important pieces of information :
1. The name of the method on which it make calls.
2. Any argument (if any) of this method.
3. The return value (if any) of this method.
What is a Function Pointer?
Function Pointers are pointers, i.e. variables, which point to the address of a function.
Types of Delegate
Delegates are of two types
1.Single Cast delegate
public delegate <return type> <delegate name>(parameters)
2.Multi Cast delegate
public delegate void <delegate name>(parameters)
Delegates are of two types
1.Single Cast delegate
public delegate <return type> <delegate name>(parameters)
2.Multi Cast delegate
public delegate void <delegate name>(parameters)
Advantage of using
Delegate
Dynamic binding can be
done by using delegate because we can call more than one methods at a time
dynamically by calling the delegate in which the methods is defined.
Example
|
namespace delgnew
{
public delegate int Delg(int x, int y);
public class Math
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
class Fun
{
static void Main(string[] args)
{
Delg del1 = new Delg(Math.Add);
int add1 = del1(7, 7);
Console.WriteLine("7
+ 7 = {0}\n", add1);
Delg del2 = new Delg(Math.Multiply);
int multiply1 = del2(7,7);
Console.WriteLine("7
* 7 = {0}", multiply1);
Console.ReadLine();
}
}
}
|
Static Delegates
Denoting static field
is meaning that it will not be modified. You can invoke delegates without
declaring a local delegate instance. Just pass in the static delegate of the
class.
Delegates as Properties
The problem with
static delegates is that they must be instantiated whether or not they
are ever used.
Event
An event might be a button push, a menu
selection in short we can cay that something happens and you must respond
to it. You cannot predict the order in which events will arise.
For example- when you click a button, it might raise the Click event. When you add to a drop-down list, it might raise a List Changed event.
For example- when you click a button, it might raise the Click event. When you add to a drop-down list, it might raise a List Changed event.
Defining Event
|
using System;
class Eventtest
{
public event EventHandler myfun
{
add
{
Console.WriteLine ("Event Fired");
}
remove
{
Console.WriteLine ("Controlled");
}
}
static void Main()
{
Eventest et = new Eventtest();
et.myfun += new EventHandler (et.DoNothing);
et.myfun -= null;
}
void DoNothing (object sender, EventArgs e)
{
}
}
|
An
event allows a class (or other object) to send notifications to other classes
(or objects) that something has occurred. In simple terms an event is the outcome
of a specific action. If you have developed programmers in graphical user
interfaces (GUI) then you are very familiar with Event handling.
When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application.
When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application.
What is Exception?
The exceptions are
anomalies that occur during the execution of a program. Exception handling is a
mechanism in .NET framework to detect
and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
In C# there are three keywords Try, Catch and Finally for handling exceptions.
In try block statements it might throw an exception whereas catch handles that caused by try block if one exists.
The finally block is used for doing any clean up process. The statement in finally block always executes.
e.g.-
and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
In C# there are three keywords Try, Catch and Finally for handling exceptions.
In try block statements it might throw an exception whereas catch handles that caused by try block if one exists.
The finally block is used for doing any clean up process. The statement in finally block always executes.
e.g.-
|
try
{ // this can cause an exception. } catch (Type x) { // for handling the exception. } finally { //this will execute. } |
Handling Exceptions
In catch block, if
don't use a brackets or arguments, we can catch all exceptions occurred inside
a try block. Even we can use a catch
block with an Exception type parameter to catch all exceptions happened inside the try block.
Since in C#, all exceptions are directly or indirectly inherited from the Exception class.
e.g.
block with an Exception type parameter to catch all exceptions happened inside the try block.
Since in C#, all exceptions are directly or indirectly inherited from the Exception class.
e.g.
|
class newexp
{ public static void Main() { int a = 0; int div = 0; try { div = 100/a; Console.WriteLine("This will not print"); } catch { Console.WriteLine("oException" ); } Console.WriteLine("Result is {0}",div); } } |
Exceptions Classes Following
are some common exception classes.
SystemException- This
exception means a failed run-time check used as a base class for other.
AccessException- This
exception means failure to access a type member, such as a method or field.
ArgumentException- This
exception means an argument to a method was invalid.
ArgumentNullException- This
exception means a null argument was passed to a method that doesn't accept it.
ArgumentOutOfRangeException-This
exception means argument value is out of range.
ArithmeticException-
This exception means arithmetic over – or underflow has
occurred.
ArrayTypeMismatchException-
This exception means attempt to store the wrong type of object
in an array.
BadImageFormatException- This
exception means image is in the wrong format.
CoreException- This
exception means base class for exceptions thrown by the runtime.
DivideByZeroException- This
exception means an attempt was made to divide by zero.
FormatException- This
exception means the format of an argument is wrong.
IndexOutOfRangeException-
This exception means an array index is out of bounds.
InvalidCastExpression- This
exception means an attempt was made to cast to an invalid class.
InvalidOperationException-
This exception means a method was called at an invalid time.
MissingMemberException- This
exception means an invalid version of a DLL was accessed.
NotFiniteNumberException- This
exception means a number is not valid.
NotSupportedException- This
exception means indicates that a method is not implemented by a class.
NullReferenceException- This
exception means attempt to use an unassigned reference.
OutOfMemoryException- This
exception means not enough memory to continue execution.
StackOverflowException- This
exception means a stack has overflow.
What is thread ?
Threads are typically
created when you want a program to do two things at once.
Starting Threads
The simplest way to
create a thread is to create a new instance of the Thread class. The Thread
constructor takes a single argument: a
delegate type. The CLR provides the ThreadStart delegate class specifically for this purpose, which points to a method you designate.
This allows you to construct a thread and to say to it "when you start, run this method." The ThreadStart delegate declaration is:-
public delegate void ThreadStart( );
delegate type. The CLR provides the ThreadStart delegate class specifically for this purpose, which points to a method you designate.
This allows you to construct a thread and to say to it "when you start, run this method." The ThreadStart delegate declaration is:-
public delegate void ThreadStart( );
Example for Creating
Thread:
|
using System;
using System.Threading;
public class CreatingThread
{
static void Main(string[] args)
{
Thread MyThread = new Thread(new ThreadStart(ThreadProc));
MyThread.Start();
MyThread.Join();
}
protected static void ThreadProcess()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
}
}
}
|
Creating a Thread of
Execution:
|
using System;
using System.Threading;
class MyThread
{
public int count;
string thrdName;
public MyThread(string name) {
count = 0;
thrdName = name;
}
public void run()
{
Console.WriteLine(thrdName + " starting.");
do {
Thread.Sleep(500);
Console.WriteLine("In " + thrdName +",
count is " + count);
count++;
} while(count < 10);
Console.WriteLine(thrdName + " terminating.");
}
}
public class MultiThread
{
public static void Main()
{
Console.WriteLine("Main thread starting.");
MyThread mt = new MyThread("Child #1");
Thread newThrd = new Thread(new ThreadStart(mt.run));
newThrd.Start();
do {
Console.Write(".");
Thread.Sleep(100);
} while (mt.count != 10);
Console.WriteLine("Main thread ending.");
}
}
|
Joining Threads
To join thread1 (t1)
onto thread2 (t2), write:
t2.Join( );
Joining the current thread to each thread in the collection in turn:
t2.Join( );
Joining the current thread to each thread in the collection in turn:
|
foreach (Thread myThread in myThreads)
{
myThread.Join( );
}
Console.WriteLine("All
my threads are done.");
|
Create multiple threads
of execution
|
using System;
using System.Threading;
class MyThread
{
public int count;
public Thread thrd;
public MyThread(string name)
{
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
void run()
{
Console.WriteLine(thrd.Name + " starting.");
do
{
Thread.Sleep(500);
Console.WriteLine("In
" + thrd.Name +", count is " + count);
count++;
} while(count < 10);
Console.WriteLine(thrd.Name + " terminating.");
}
}
public class MoreThreads {
public static void Main() {
Console.WriteLine("Main
thread starting.");
MyThread mt1 = new MyThread("Child #1");
MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");
do
{
Console.Write(".");
Thread.Sleep(100);
} while (mt1.count < 10 || mt2.count < 10 || mt3.count < 10);
Console.WriteLine("Main
thread ending.");
}
}
|
Suspending Threads
To cause your thread
to sleep for one second, you can invoke the static method of Thread, Sleep,
which suspends the thread in which it is
invoked:
Thread.Sleep(1000);
invoked:
Thread.Sleep(1000);
Killing Threads
For killing a thread
Abort( ) method is used. This causes a ThreadAbortException exception to be
thrown, which the thread can catch,
and thus provides the thread with an opportunity to clean up any resources it might have allocated.
and thus provides the thread with an opportunity to clean up any resources it might have allocated.
catch (ThreadAbortException)
{
Console.WriteLine("[{0}] Aborted! Cleaning up...",
Thread.CurrentThread.Name);
}
Example for Suspending, resuming, and stopping a
thread:
|
using System;
using System.Threading;
class MyThread {
public Thread thrd;
public MyThread(string name) {
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
void run() {
Console.WriteLine(thrd.Name + " starting.");
for(int i = 1; i <= 1000; i++) {
Console.Write(i + "
");
if((i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);
}
}
Console.WriteLine(thrd.Name + " exiting.");
}
}
public class SuspendResumeStop {
public static void Main() {
MyThread mt1 = new MyThread("My Thread");
Thread.Sleep(1000); // let child thread start executing
mt1.thrd.Suspend();
Console.WriteLine("Suspending
thread.");
Thread.Sleep(1000);
mt1.thrd.Resume();
Console.WriteLine("Resuming
thread.");
Thread.Sleep(1000);
mt1.thrd.Suspend();
Console.WriteLine("Suspending
thread.");
Thread.Sleep(1000);
mt1.thrd.Resume();
Console.WriteLine("Resuming
thread.");
Thread.Sleep(1000);
Console.WriteLine("Stopping
thread.");
mt1.thrd.Abort();
mt1.thrd.Join(); // wait for thread to terminate
Console.WriteLine("Main
thread terminating.");
}
}
|
Synchronization
Synchronization
is provided by a lock on the object, which prevents a second thread from
barging in on your
object
until the first thread is finished with it.
Microsoft Visual StudioVisual Studio is an integrated development environment (IDE) developed by Microsoft. It can be used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all platforms supported by Microsoft Windows, Windows Mobile, Windows CE.
Architecture
It does not support any programming language, solution or tool intrinsically. Instead, it allows plugging in various types of functionality, that is coded as a VSPackage.
The IDE provides three services:
SVsSolution, which provides the ability to enumerate projects and solutions; SVsUIShell, which provides windowing and UI functionality (including tabs, toolbars and tool windows)
SVsShell, which deals with registration of VSPackages.
In addition, the IDE also manages for coordinating and enabling communication between services. All editors, designers, project types and other tools are implemented as VSPackages. Visual Studio uses COM to access the VSPackages. The Visual Studio SDK also includes the Managed Package Framework (MPF), which is a set of managed wrappers around the COM-interfaces that allow the Packages to be written in any CLI compliant language. However, MPF does not provide all the functionality exposed by the Visual Studio COM interfaces. The services can then be consumed for creation of other packages, which add functionality to the Visual Studio IDE.
Features of Microsoft Visual Studio
Code editor
Code editor that supports syntax highlighting and code completion using IntelliSense for not only variables, functions and methods but also language constructs like loops and queries.
Debugger
It works both as a source-level debugger and as a machine-level debugger. It works with both managed code as well as native code and can be used for debugging applications written in any language supported by Visual Studio.
Designer
It includes a host of visual designers to aid in the development of applications. These tools includes:-
Windows Forms Designer
It includes a palette of UI widgets and controls (including buttons, progress bars, labels, layout containers and other controls) that can be dragged and dropped on a form surface.
WPF(Windows Presentation Foundation) Designer
It is used to author user interfaces targeting Windows Presentation Foundation. It supports all WPF functionality including data binding and automatic layout management.
Web designer/development
It is used for developing ASP.NET applications and supports HTML, CSS and JavaScript. It uses a code-behind model to link with ASP.NET code. From Visual Studio 2008 onwards, the layout engine used by the web designer is shared with Microsoft Expression Web.
Class designer
The Class Designer can generate C# and VB.NET code outlines for the classes and methods. It can also generate class diagrams from hand-written classes.
Data designer
The data designer can be used to graphically edit database schemas, including typed tables, primary and foreign keys and constraints. It can also be used to design queries from the graphical view.
Mapping designer
The mapping designer is used by LINQ to SQL to design the mapping between database schemas and the classes that encapsulate the data.
Other tools
ToolBox Explorer
Open Tabs Browser
It is used to list all open tabs and to switch between them. It is invoked using CTRL+TAB.
Properties Editor
It is used to edit properties in a GUI pane inside Visual Studio.
Object Browser
It can be used to browse the namespaces (which are arranged hierarchically) in managed assemblies.
Solution Explorer
It is used to manage and browse the files in a solution.
Team Explorer
It is used to integrate the capabilities of Team Foundation Server, the Revision Control System into the IDE (and the basis for Microsoft's CodePlex hosting environment for open source projects). In addition to source control it provides the ability to view and manage individual work items (including bugs, tasks and other documents) and to browse TFS statistics.
Data Explorer
It is used to manage databases on Microsoft SQL Server instances.
Server Explorer
It tool is used to manage database connections on an accessible computer.
Included products
Microsoft Visual C++
It is Microsoft's implementation of the C and C++ compiler and associated languages-services and specific tools for integration with the Visual Studio IDE.
Microsoft Visual C#
Microsoft's implementation of the C# language, targets the .NET Framework, along with the language services that lets the Visual Studio IDE support C# projects.
Microsoft Visual Basic
Microsoft's implementation of the VB.NET language and associated tools and language services. It was introduced with Visual Studio .NET (2002).
Good job..Keep it up.
ReplyDeletenycc work!!
ReplyDeleteExcellent Work.!!!Keep posting..
ReplyDeletecan u please briefly about delegates and event in c#.net and send the link to my email id thulasiayya1990@gmail.com
ReplyDeleteit helps me lot.
ReplyDeletegreat blog to read
ReplyDeletedot net training | best dot net training | dot net training and placement | dot net training in chennai
It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training institute in velachery
ReplyDeleteStill referrin to this in 2018 since 2016. Thank you for your effort.
ReplyDeleteIt 's excellent posting
ReplyDelete.Net Online Training Bangalore