C # Programming
This
Article is about a programming language. For other uses, see C –Sharp
disambiguation. The correct title of this article is C# programming language. The
substitution or omission of the # is because of technical restrictions.
C#
pronounced see sharp is a multi paradigm programming language encompassing
strong typing, imperative, declarative, functional, procedural, generic,
object- oriented class based, and component oriented programming disciplines. It
was developed by Microsoft within its DOT NET initiative and later approved as a
standard by Ecma. C# is built on the syntax and semantics of C++, allowing c
programmers to take advantage of DOT NET and the common language run time.
C# is
intended to be a simple, modern, general purpose, object oriented programming
language. Its development team is lead by Anders Hejlsberg.
This section provides detailed information on key
C# language features and features accessible to C# through the .NET Framework.
Most of this section assumes that you already
know something about C# and general programming concepts. If you are a complete
beginner with programming or with C#, you might want to visit the, where you
can find many tutorials, samples and videos to help you get started.
For information about specific keywords,
operators and coprocessor directives, see. For information about the C#
Language Specification, see C# language specification.
Although C# is derived from the, it introduces
some unique and powerful features, such as delegates which can be viewed as
type-safe function pointers and lambda expressions which introduce elements of
functional programming languages, as well as a simpler single class inheritance
model than C++ and, for those of you with experience in C-like languages, a very familiar syntax that may help beginners
become proficient faster than its predecessors. Similar to, comes with an
extensive class library, and supports exception handling, multiple types
of, and separation of interfaces from implementations. Those features, combined
with its powerful development tools, multi-platform support, and generics,
make C# a good choice for many types of software development projects,
projects, projects implemented by individuals or large or small teams, Internet
applications, and projects with strict reliability requirements. Testing
frameworks such as and thus a good language for use with XP. Its helps to
prevent many programming errors that are common in weakly typed languages.
C # pronounced See Sharp is a multipurpose computer suitable for a wide variety
of development needs. This Wiki book introduces C# language fundamentals and
covers a variety of the base class
libraries provided by the Microsoft .NET Framework.
C# is a modern and innovative programming
language that carefully incorporates features found in the most common industry
and research languages. In keeping with the design philosophy of C#, Microsoft
has introduced several potential new features to the C# language that increase
developer productivity with language constructs.
Explains
C#
The
term’s # character derives its name from the musical sharp key, which denotes a
one semitone pitch increase. C# is pronounced see sharp.
C# improved and updated many C and C++ features,
including the following,
C#
has a strict Boolean data variable type, such as bool, whereas C++ bool
variable types may be returned as integers or pointers to avoid common
programming errors.
C#
automatically manages inaccessible object memory using a garbage collector,
which eliminates developer concerns and memory leaks.
C#
type is safer than C++ and has safe default conversions only, which are
implemented during compile or runtime.
No
implicit conversions between Booleans, enumeration members and integers may be
converted to an enumerated type. User-defined conversions must be specified as
explicit or implicit, versus the C++ default implicit conversion operators and
copy constructors.
C# is a general object-oriented programming language for networking and Web
development. C# is specified as a common
language infrastructure language.
Dutch software engineer Anders Hejlsberg formed a team to develop C# as a complement to Microsoft’s NET framework. Initially, C# was developed as C-Like Object Oriented Language. The actual name was changed to avert potential trademark issues.
Dutch software engineer Anders Hejlsberg formed a team to develop C# as a complement to Microsoft’s NET framework. Initially, C# was developed as C-Like Object Oriented Language. The actual name was changed to avert potential trademark issues.
C # Definition
C
sharp an object-oriented programming language that is based on C++ with
elements from Visual Basic and Java. Like Java, C# provides automatic garbage
collection, whereas traditional C and C++ do not. C# was created by Microsoft
and also standardized by the European Computer Manufacturers Association.
Microsoft designed C# as its flagship programming language for the .NET
environment.
C# pronounced C-sharp is an language from Microsoft that aims to combine the
computing power of with the programming ease of. C# is based on C++ and
contains features similar to those of C# is designed to work with Microsoft's
platform. Microsoft's aim is to facilitate the exchange of information and
services over the Web, and to enable developers to build highly applications.
C# simplifies programming through its use of Extensible Markup Language and
Simple Object Access Protocol which allow access to a programming or without requiring the programmer to write
additional code for each step. Because programmers can build on existing code,
rather than repeatedly duplicating it, C# is expected to make it faster and
less expensive to get new products and services to market.
Microsoft is collaborating with ECMA, the international
standards body, to create a standard for C#. International Standards
Organization recognition for C# would encourage other companies to develop
their own versions of the language. Companies that are already using C# include
Apex Software, Bunka Orient, Component Source, devSoft, FarPoint Technologies,
LEAD Technologies, Prototype, and Seagate Software.
Categories
of data types
CTS separate data types into two categories,
- Reference types
- Value types
Instances
of value types do not have referential identity or referential comparison
semantics - equality and inequality comparisons for value types compare the
actual data values within the instances, unless the corresponding operators are
overloaded. Value types are derived from System.Value Type, always have a
default value, and can always be created and copied. Some other limitations on
value types are that they cannot derive from each other but can implement
interfaces and cannot have an explicit default parameter less constructor.
Examples of value types are all primitive types, such as int a signed 32-bit
integer, float a 32-bit floating-point number, char a 16-bit Unicode code
unit, and System. Date Time identifies a specific point in time with nanosecond
precision. Other examples are enum and struct user defined structures.
In
contrast, reference types have the notion of referential identity - each
instance of a reference type is inherently distinct from every other instance,
even if the data within both instances is the same. This is reflected in
default equality and inequality comparisons for reference types, which test for
referential rather than structural equality, unless the corresponding operators
are overloaded such as the case for System. String. In general, it is not
always possible to create an instance of a reference type, nor to copy an
existing instance, or perform a value comparison on two existing instances,
though specific reference types can provide such services by exposing a public
constructor or implementing a corresponding interface such as ICloneable or
IComparable. Examples of reference types are object the ultimate base class for
all other C# classes, System.String a string of Unicode characters, and
System.Array a base class for all C# arrays.
Preprocessor
C#
features preprocessed directives
that allow programmers to define, but not macros. Conditionals such as #if,
#endif, and #else are also provided. Directives such as #region give hints to
editors for code folding.
public class Foo
{
#region
Constructors
public Foo()
{}
public
Foo(int firstParam) {}
#endregion
#region
Procedures
public void
IntBar(int firstParam) {}
public void
StrBar(string firstParam) {}
public void
BoolBar(bool firstParam) {}
#endregion
}
Implementations
The reference C# compiler is which closed-source is.
Other C# compilers exist, often including an
implementation of the and the DOT NET class libraries up to .NET 2.0,
The
project provides a C# compiler, a complete open source implementation of the
Common Language Infrastructure including the required framework libraries as
they appear in the ECMA specification and a nearly complete implementation of
the Microsoft proprietary DOT NET class libraries up to DOT NET 3.5. As of Mono 2.6,
no plans exist to implement, is planned for a later release; and there are only
partial implementations,
The
project also provides an open source C# compiler, a nearly complete
implementation of the Common Language Infrastructure including the required
framework libraries as they appear in the ECMA specification, and subset of
some of the remaining Microsoft proprietary DOT NET class libraries up to DOT NET 2.0
those not documented or included in the ECMA specification, but included in
Microsoft's standard DOT NET Framework distribution.
Microsoft's
Rotor project currently called licensed for educational and research use only
provides a implementation of the CLR runtime and a C# compiler, and a subset of
the required framework libraries in the ECMA specification up to C# 2.0, and
supported on Windows XP only.
What is C#
C# pronounced see
sharp or C Sharp is one of many
.NET programming languages. It is object-oriented and allows you to build
reusable components for a wide variety of application types Microsoft
introduced
C# is an evolution of the C and C++ family of
languages. However, it borrows features from other programming languages, such
as Delphi and Java. If you look at the most basic syntax of both C# and Java,
the code looks very similar, but then again, the code looks a lot like C++ too,
which is intentional. Developers often ask questions about why C# supports
certain features or works in a certain way. The answer is often rooted in its
C++ heritage.
Pounced
See Sharp a hybrid of C and C++, it
is a Microsoft programming language developed to compete with Sun’s java
language. C # is an object oriented programming language used with XML based
Web service on the DOT NET platform and designed for improving productivity in
the development of Web application. C# boasts type- safety, garbage collection,
simplified type declarations, versioning and scalability support, and other
features that make developing solutions faster and easier, especially for COM+
and web services. Microsoft critics have pointed to the similarities between C#
and Java.
Microsoft C#
A
number of developers have begun building software using the C# programming
language. Even within Microsoft, C# has been used to build several shipping
applications, including the .NET Framework, MSN Web properties, and the Tablet
PC SDK. As such, C# has proven itself as a language suitable for the
construction of high-quality commercial software.
Many of the features in the C# language were
created with four different design goals in mind,
A
unified type system and simplifying the way that value and reference types are
used by the language.
A
component-based design established through features such as XML comments,
attributes, properties, events and delegates.
Practical
developer headroom established through the unique capabilities of the C#
language, including safe pointer manipulation, overflow checking, and more.
Pragmatic
language constructs, such as the foreach and using statements, which improve
developer productivity.
In the Visual
Studio for Yukon version of the C# language, Microsoft plans to build on an
already elegant and expressive syntax by incorporating a variety of features
across a broad spectrum of research and industry languages. Included among
these language features are generics, iterates, anonymous methods and partial
types.
C #
Explanations
C#
is one of the most used programming languages today. It is based on the
concepts of C++, and is very similar to Java. If you know either of these
languages, you should be able to quite easily. You can then develop C#
applications and run them on the currently popular DOT NET framework.
Classes, Members and
Objects
The
most basic building block of a C# code are classes and objects. Every
class has members that define the data and behavior of the class. Objects are
real instances of a class. You can give public or private access to the classes
defined in your program. Private classes can have only one object instance,
which helps to hide data from the rest of the code. You need to start and end a
class definition with left and right curly brackets respectively, this forms
the class body.
Methods
You
will find the mention of methods in any, Besides classes, you have methods, and
each name is followed by a pair of open and close brackets. These carry out
specific functions and enable you to break down the code in a modular fashion
for the sake of simplicity. Every C# code starts off with the Main method. This
is a static method, and can thus be accessed only by classes, and not by
objects.
Variables
All
data is stored using variables, each having a name and type. The data that you
can assign to a variable is limited by its data type. For example, integer
value cannot be assigned to a string variable. The value of a variable may
change during the execution of the program. If there is no value assigned, the
default value is taken for that data type.
Constants
The
other elements that holds data in a C# program are constants; these have fixed
values that are set during initialisation. These are preceded by the keyword const. For example,
const int X = 5;
It
is a good practice to write the names of constants in upper case for the sake
of readability, although the compiler would process it the same even if it were
written in lower case.
Arrays
Like
C and C++, C# also includes arrays. The difference here is that the square
brackets that indicate the position of the array elements follow the type and
not the array name or identifier. For example,
int[] samplearray;
Note
that this declaration is not enough to create an actual instance of the array.
You can do this as follows,
int[] samplearray = new
int[3];
If
you want to assign values to this array, include them within curly braces right
after int[3] in the above statement.
Array
indexing begins at zero. The size of an array is not fixed at the time it is
defined; the number of elements within it can be changed anytime during the
code. Square brackets following the array name allow you to access
individual elements.
C# Application Run
An important point is that C# is a managed language, meaning that it
requires the to execute. Essentially, as an application that is written in C#
executes, the CLR is managing memory, performing garbage collection, handling
exceptions, and providing many more services that you, as a developer, don't
have to write code for. The C# compiler produces Intermediate Language, rather
than machine language, and the CLR understands IL. When the CLR sees the IL, it
Just-In-Time compiles it, method by method, into compiled machine code in
memory and executes it. As mentioned previously, the CLR manages the code as it
executes.
Because C# requires the CLR, you must have the CLR
installed on your system. All new Windows operating systems ship with a version
of the CLR and it is available via Windows Update for older systems. The CLR is
part of the DOT NET, so if you see updates for the DOT NET Framework Runtime, it
contains the CLR and DOT NET Framework Class Library. It follows that if you copy
your C# application to another machine, then that machine must have the CLR
installed too.
C # in Advanced Topics
Inheritance: Re-using
existing code to improve or specialize the functionality of an object.
Interfaces: Define
a template, on which to base sub-classes.
Delegated and Events: Learn
about delegates, anonymous delegates, lambda expressions, and events.
Abstract Classes: Build partially
implemented classes.
Partial classes: Split a class
over several files to allow multiple users to develop, but also to stop code
generators interfering with source code.
Generics: Allow commonly used collections and
classes to appear to have specialization for your custom class.
Extension Methods:
Extend
the functionality of existing types.
Object Life Time: Learn about the
lifetime of objects, where they are allocated and learn about garbage
collection.
Design Patterns: Learn commonly used design
methodologies to simplify and/or improve your development framework.
C # Basic
Basic Syntax: Describes the basics in how the
applications you write will be interpreted.
Naming Conventions:
Quickly describes the generally accepted naming conventions for C#.
Variables: The
entities used to store data of various shapes.
Operators:
Summarizes the operators, such as the '+' in addition, available in C#.
Data structures: Enumerations, struct, and more.
Control Statement: Loops,
conditions, and more. How the program flow is controlled.
Exceptions:
Responding to errors that can occur.
Libraries
The
C# specification details a minimum set of types and class libraries that the
compiler expects to have available. In practice, C# is most often used with
some implementation of the CLI, which is standardized as Common Language Infrastructure.
C # Data Types
There are Types in C #
1. Value
Types
2. Reference
Types
3. Object
Types
4. Dynamic
Types
5. String
Types
6. Pointer
Types
Value type
variables can be assigned a value directly. They are derived from the class System.Value Type.
The value types directly contain data. Some
examples are int, char, float, which stores numbers, alphabets, and floating
point numbers, respectively. When you declare an int type, the system
allocates memory to store the value.
Reference Types
The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.
In
other words, they refer to a memory location. Using more than one variable, the
reference types can refer to a memory location. If the data in the memory
location is changed by one of the variables, the other variable automatically
reflects this change in value. Example of built-in reference types are, object,
dynamic and string.
Object Types
The
Object
Type is the ultimate base class for all data types in C# Common Type System. Object is an alias
for System. Object class. So object types can be assigned values of any other
types, value types, and reference types, predefined or user-defined types.
However, before assigning values, it needs type conversion.
When
a value type is converted to object type, it is called boxing and on the
other hand, when an object type is converted to a value type, it is called unboxing.
Object
obj;
Obj
= 100;
Dynamic Types
You
can store any type of value in the dynamic data type variable. Type checking
for these types of variables takes place at run-time.
Syntax
for declaring a dynamic type is:
dynamic
= value;
Dynamic types are similar to object
types except that type checking for object type variables takes place at
compile time, whereas that for the dynamic type variables take place at run
time.
String Type
The
String
Type allows you to assign any string values to a variable. The
string type is an alias for the System.String class. It is derived from object
type. The value for a string type can be assigned using string literals in two
form,
String str = Tutorials Point;
Pointer Types
Pointer type
variables store the memory address of another type. Pointers in C# have the
same capabilities as in C or C++.
Syntax for declaring a pointer type is:
type* identifier;
C #
Operator Over Loading
You can redefine or overload most of the
built-in operators available in C#. Thus a programmer can use operators with
user-defined types as well. Overloaded operators are functions with special
names the keyword operator followed by the symbol for the operator being
defined. Like any other function, an overloaded operator has a return type and
a parameter list. For Example
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
Overloadable and Non-Overloadable Operators
The following table describes the overload ability of
the operators in C#,
Operators
|
Description
|
+, -, !, ~, ++, --
|
These unary operators take one operand and can
be overloaded.
|
+, -, *, /, %
|
These binary operators take one operand and
can be overloaded.
|
==, !=, <, >, <=, >=
|
The comparison operators can be overloaded
|
&&, ||
|
The conditional logical operators cannot be
overloaded directly.
|
+=, -=, *=, /=, %=
|
The assignment operators cannot be overloaded.
|
=, ., ?:, ->, new, is, sizeof, typeof
|
These operators cannot be overloaded.
|
C# - Multithreading
A thread is defined as the execution
path of a program. Each thread defines a unique flow of control. If your
application involves complicated and time consuming operations then it is often
helpful to set different execution paths or threads, with each thread
performing a particular job.
Threads are lightweight processes. One common
example of use of thread is implementation of concurrent programming by modern
operating systems. Use of threads saves wastage of CPU cycle and increase
efficiency of an application.
So far we have written programs where a single
thread runs as a single process which is the running instance of the
application. However, this way the application can perform one job at a time.
To make it execute more than one task at a time, it could be divided into
smaller threads.
Thread
Life Cycle
The
life cycle of a thread starts when an object of the System.Threading.Thread
class is created and ends when the thread is terminated or completes execution.
Following are the various states in the life
cycle of a thread,
The Unstarted State: It is the situation when the instance of the thread is created but the Start
method has not been called.
The Ready State: It is the situation when the thread is ready to run
and waiting CPU cycle.
The Not Runnable State: a
thread is not runnable, when:
- Sleep method has been called
- Wait method has been called
- Blocked by I/O operations
The Dead State: It
is the situation when the thread has completed execution or has been aborted.
The
Main Thread
In
C#, the System.Threading.Thread class is used for working with
threads. It allows creating and accessing individual threads in a multithreaded
application. The first thread to be executed in a process is called the main
thread.
When
a C# program starts execution, the main thread is automatically created. The
threads created using the Thread class are called the child
threads of the main thread. You can access a thread using the CurrentThread
property of the Thread class.
using System;
using System. Threading;
namespace Multithreading Application
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
Creating Threads
Threads
are created by extending the Thread class. The extended Thread class then calls
the Start() method to begin the child thread execution.
The
following program demonstrates the concept,
using System;
using System.Threading;
namespace MultithreadingApplication
{
class
ThreadCreationProgram
{
public
static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
static
void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In
Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
When
the above code is compiled and executed, it produces the following result,
In Main: Creating the Child thread
Child thread starts
Managing
Threads
The
Thread class provides various methods for managing threads.
The
following example demonstrates the use of the sleep() method for
making a thread pause for a specific period of time.
using System;
using System.Threading;
namespace MultithreadingApplication
{
class
ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new
Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
When the above code
is compiled and executed, it produces the following result,
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes
Destroying Threads
The
Abort()
method is used for destroying threads.
The runtime aborts
the thread by throwing a ThreadAbortException.
This exception cannot be caught, the control is sent to the finally
block, if any.
Why Use C#
C#
is an elegant, simple, type-safe, object-oriented language that allows
enterprise programmers to build a breadth of applications.
C# also gives you the capability to build
durable system-level components by virtue of the following features,
Full
COM/Platform support for existing code integration.
Robustness
through garbage collection and type safety.
Security
provided through intrinsic code trust mechanisms.
Full
support of extensible metadata concepts.
You
can also interoperate with other languages, across platforms, with legacy data,
by virtue of the following features,
Full
interoperability support through COM+ 1.0 and .NET Framework services with
tight library-based access. XML support for Web-based component interaction. Versioning
to provide ease of administration and deployment.
C # Language and the DOT NET Framework
C# is an
elegant and type-safe object-oriented language that enables developers to build
a variety of secure and robust applications that run on the .NET Framework. You
can use C# to create Windows client applications, XML Web services, distributed
components, client-server applications, database applications, and much, much
more. Visual C# provides an advanced code editor, convenient user interface
designers, integrated debugger, and many other tools to make it easier to
develop applications based on the C# language and the DOT NET Framework.
C # Language
C#
syntax is highly expressive, yet it is also simple and easy to learn. The
curly-brace syntax of C# will be instantly recognizable to anyone familiar with
C, C++ or Java. Developers who know any of these languages are typically able
to begin to work productively in C# within a very short time. C# syntax
simplifies many of the complexities of C++ and provides powerful features such
as null able value types, enumerations, delegates, lambda expressions and
direct memory access, which are not found in Java. C# supports generic methods
and types, which provide increased type safety and performance, and iterates,
which enable implementers of collection classes to define custom iteration
behaviours that are simple to use by client code. Language-Integrated Query expressions make the strongly-typed query
a first-class language construct.
As
an object-oriented language, C# supports the concepts of encapsulation,
inheritance, and polymorphism. All variables and methods, including the Main
method, the application's entry point, are encapsulated within class
definitions. A class may inherit directly from one parent class, but it may
implement any number of interfaces. Methods that override virtual methods in a
parent class require the override keyword as a way to avoid accidental
redefinition. In C#, a struct is like a lightweight class, it is a
stack-allocated type that can implement interfaces but does not support
inheritance.
No comments:
Post a Comment