Sie sind auf Seite 1von 65

Unit 1

C # Programming
• C# (pronounced "C-sharp") is an object-
oriented programming language from
Microsoft that aims to combine the
computing power of C++ with the
programming ease of Visual Basic. C# is based
on C++ and contains features similar to those
of Java.
Features of C#
• C# is a modern, general-purpose, object-oriented
programming language .
• It was developed by Microsoft.
• C# was developed by Anders Hejlsberg.
• It is component oriented.
• It is easy to learn.
• It is a structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• It is a part of .Net Framework.
MAIN FEATURES OF C#
1. SIMPLE
• Pointers are missing in C#.
• Unsafe operations such as direct memory manipulation are not allowed.
• In C# there is no usage of "::" or "->" operators.
• Since it's on .NET, it inherits the features of automatic memory management and
garbage collection.
• Varying ranges of the primitive types like Integer, Floats etc.
• Integer values of 0 and 1 are no longer accepted as boolean values.Boolean values
are pure true or false values in C# so no more errors of "="operator and
"=="operator.
• "==" is used for comparison operation and "=" is used for assignment operation.
2. MODERN
• C# has been based according to the current trend and is very powerful and simple
for building interoperable, scable, robust applications. C# includes built in support
to turn any component into a web service that can be invoked over the internet
from any application running on any platform.
3. OBJECT ORIENTED
• C# supports Data Encapsulation, inheritance, polymorphism, interfaces.
• (int,float, double) are not objects in java but C# has introduces structures(structs)
which enable the primitive types to become objects.int i=1;
string a=i Tostring(); //conversion (or) Boxing
The Common Language Infrastructure supports a two-
step compilation process

• Compilation
– The C# compiler: Translation of C# source to CIL
– Produces .dll and .exe files
– Just in time compilation: Translation of CIL to machine
code
• Execution
– With interleaved Just in Time compilation
– On Mono: Explicit activation of the interpreter
– On Window: Transparent activation of the interpreter
4. TYPE SAFE
• In C# we cannot perform unsafe casts like convert double to a boolean.Value types
(priitive types) are initialized to zeros and reference types (objects and classes) are
initialized to null by the compiler automatically.arrays are zero base indexed and
are bound checked.Overflow of types can be checked.
5. INTEROPERABILITY
• C# includes native support for the COM and windows based applications.
• Allowing restriced use of native pointers.
• Users no longer have to explicitly implement the unknown and other COM
interfacers, those features are built in.
• C# allows the users to use pointers as unsafe code blocks to manipulate your old
code.
• Components from VB NET and other managed code languages and directlyt be
used in C#.
6. SCALABLE AND UPDATEABLE
• .NET has introduced assemblies which are self describing by means of their
manifest. manifest establishes the assembly identity, version, culture and digital
signature etc. Assemblies need not to be register anywhere.To scale our
application we delete the old files and updating them with new ones. No
registering of dynamic linking library.Updating software components is an error
prone task. Revisions made to the code. can effect the existing program C# support
versioning in the language. Native support for interfaces and method overriding
enable complex frame works to be developed and evolved over time.
Code Execution Process
Compiler time process.

• The .Net framework has one or more language compliers, such as


Visual Basic, C#, Visual C++, JScript, or one of many third-party
compilers such as an Eiffel, Perl, or COBOL compiler.
• Any one of the compilers translate your source code into Microsoft
Intermediate Language (MSIL) code.
• For example, if you are using the C# programming language to
develop an application, when you compile the application, the C#
language compiler will convert your source code into Microsoft
Intermediate Language (MSIL) code.
• In short, VB.NET, C# and other language compilers generate MSIL
code. (In other words, compiling translates your source code into
MSIL and generates the required metadata.)
• Currently "Microsoft Intermediate Language" (MSIL) code is also
known as "Intermediate Language" (IL) Codeor "Common
Intermediate Language" (CIL) Code.
Runtime process.
• The Common Language Runtime (CLR) includes a JIT
compiler for converting MSIL to native code.
• The JIT Compiler in CLR converts the MSIL code into
native machine code that is then executed by the OS.
• During the runtime of a program the "Just in Time"
(JIT) compiler of the Common Language Runtime (CLR)
uses the Metadata and converts Microsoft
Intermediate Language (MSIL) into native code.

BYTE CODE (MSIL + META DATA) ----- Just-In-Time (JIT)


compiler------> NATIVE CODE
Keywords in C#
Namespace
• A namespace is designed for providing a way
to keep one set of names separate from
another.
• The class names declared in one namespace
does not conflict with the same class names
declared in another.
Defining a Namespace

namespace namespace_name
{
// code declarations
}
• To call the namespace
namespace_name.item_name;
using System;
namespace first_space
{ class namespace_cl {
public void func()
{ Console.WriteLine("Inside first_space");
}}}
namespace second_space
{ class namespace_cl {
public void func()
{ Console.WriteLine("Inside second_space");
}}}
class TestClass
{ static void Main(string[] args)
{ first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey(); } }
Output:
Inside first_space
Inside second_space
using System;

• The using keyword states that the program is


using the names in the given namespace. For
example, we are using the System namespace
in our programs.
• The class Console is defined there. We just
write −
• Console.WriteLine ("Hello there");
Basic principles of object oriented
programming
• Objects:
– An object is just a simplification of something that
you wish to use in your program.
– A class is a template used to describe an object.
– A class is an abstraction of some object you observe
in the real world.
– You can break a class down into two basic
components:
– 1. Those properties that describe the object, and 2.
those methods , or actions, that you wish to associate
with the object.
• Class Properties :
– The class properties are the data that you want to
record and associate with an object.

•The state of an object is determined by the values of the


properties used to describe the object. In our example, the
properties used to describe the state of a class person object are
those shown in Table 2 - 1 .
•Just keep in mind that anytime the value of a property changes,
the state of the object — by definition — also changes.
Class Methods
• Just as there are property values that define the
state of an object, there are usually class methods
that act on the properties.
• In short, the class methods determine the
behaviors the object is capable of performing
• Methods are used to describe whatever actions
you wish to associate with the object.
• Methods often are used to manipulate the data
contained within the object.
• For example: class methods are used to take one
or more property values, process the data those
properties contain, and create a new piece of data.
I Have an Object . . . Now What?
• myFriend.Name = “Issy”;
• myFriend.Gender = “F”;
• myFriend.Height = 59;
• myFriend.Build = “Petite”;
• myFriend.hairColor = “Blonde”;
• myFriend.eyeColor = “Blue”;
• myFriend.Clothing = “Business casual”;
• myFriend.Accessories = “Tan leather briefcase”;
Program 1
using System;
namespace HelloWorldApplication
{ class HelloWorld
{ static void Main(string[] args)
{ /* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey(); } } }
• The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.
• The next line has the namespace declaration. A namespace is a collection of
classes. The HelloWorldApplication namespace contains the class HelloWorld.
• The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple
methods. Methods define the behavior of the class. However, the HelloWorld class
has only one method Main.
• The next line defines the Main method, which is the entry point for all C#
programs. The Main method states what the class does when executed.
• The next line /*...*/ is ignored by the compiler and it is put to addcomments in the
program.
• The Main method specifies its behavior with the
statementConsole.WriteLine("Hello World");
• WriteLine is a method of the Console class defined in the Systemnamespace. This
statement causes the message "Hello, World!" to be displayed on the screen.
• The last line Console.ReadKey(); is for the VS.NET Users. This makes the program
wait for a key press and it prevents the screen from running and closing quickly
when the program is launched from Visual Studio .NET.
.Net Framework
• The Microsoft .Net Framework is a platform that
provides tools and technologies you need to build
Networked Applications as well as Distributed
Web Services and Web Applications.
• The .Net Framework provides the necessary
compile time and run-time foundation to build
and run any language that conforms to the
Common Language Specification (CLS).

The main two components of .Net Framework


• Framework Class Library (FCL)
• Common Language Runtime (CLR)
Framework Class Library (FCL)

• It provides language interoperability (each


language can use code written in other
languages) across several programming
languages.
• FCL provides user interface, data access,
database connectivity, cryptography, web
application development, numeric algorithms,
and network communications.
Common Language Runtime (CLR)

• The Common Language Runtime (CLR), the


virtual machine component of Microsoft's
.NET framework, manages the execution of
.NET programs.
• A process known as just-in-time compilation
converts compiled code into machine instructions
which the computer's CPU then executes. ... All
versions of the .NETframework include CLR.
• (As such, computer code written using .NET
Framework is called "managed code".)
VB C++ C# Jscript ----

Common Language Specification (CLS)

Web Application Windows Application

ADO.NET and XML

Base Class Library

Common Language Runtime (CLR)

Operating System
A Common Language
Specification (CLS)
• A Common Language Specification (CLS) is a
document that says how computer
programs can be turned into MSIL code. When
several languages use the same bytecode,
different parts of a program can be written in
different languages. Microsoftuses a Common
Language Specification for their .NET
Framework.
The Base Class Library (BCL)
• The Base Class Library (BCL) is literally that,
thebase. It contains basic, fundamental types
like System.String and System.DateTime .
TheFramework Class Library (FCL) is the
wider librarythat contains the
totality: ASP.NET, WinForms, the XML stack,
ADO.NET and more. You could say that the FCL
includes the BCL.
WPF
• WPF : Windows Presentation Foundation
(or WPF) is a graphical subsystem by Microsoft
for rendering user interfaces in Windows-
based applications. WPF, previously known as
"Avalon", was initially released as part of .NET
Framework 3.0 in 2006.
LINQ
• LINQ (Language Integrated Query) allows
writing queries even without the
knowledge of query languages like SQL,
XML etc. LINQ queries can be written for
diverse data types.
WCF
• WCF stands for Windows Communication
Foundation. It is a framework for building,
configuring, and deploying network-
distributed services. Earlier known as Indigo, it
enables hosting services in any type of
operating system process.
ADO.NET
• ADO.NET(ActiveX Data Objects ) is a data
access technology from the Microsoft
.NETFramework that provides communication
between relational and non-relational systems
through a common set of
components.ADO.NET is a set of computer
software components that programmers can
use to access data and data services from the
database.
ASP.NET
• ASP.NET is a web application framework
developed and marketed by Microsoft to
allow programmers to build dynamic web
sites. It allows you to use a full featured
programming language such as C# or VB.NET
to build web applications easily.
• You can see Operating System at the base. It
can be any Microsoft windows platform that
support Visual Studio .NET.
/*
* C# Program to Find Roots of a Quadrati
c Equation
*/
using System;

namespace example }
{ public void compute()
class Quadraticroots {
{ int m;
double a, b, c; double r1, r2, d1;
d1 = b * b - 4 * a * c;
public void read() if (a == 0)
{ m = 1;
Console.WriteLine(" \n To find the roots o else if (d1 > 0)
f a quadratic equation of the form a*x*x + b m = 2;
*x + c = 0"); else if (d1 == 0)
Console.Write("\n Enter value for a : "); m = 3;
a = double.Parse(Console.ReadLine()); else
Console.Write("\n Enter value for b : "); m = 4;
b = double.Parse(Console.ReadLine());
Console.Write("\n Enter value for c : ");
c = double.Parse(Console.ReadLine());
switch (m) ”+”+” i” + r2);
{ Console.WriteLine("\n First root is “+r1+”-”+” i” + r
case 1: Console.WriteLine("\n Not a Quadr 2);
atic equation, Linear equation");
Console.ReadLine(); Console.ReadLine();
break; break;
case 2: Console.WriteLine("\n Roots are Re }
al and Distinct"); }
r1 = (-b + Math.Sqrt(d1)) / (2 * a); }
r2 = (-b - Math.Sqrt(d1)) / (2 * a);
Console.WriteLine("\n First root is “+ r1); class Roots
Console.WriteLine("\n Second root is “+ r2); {
Console.ReadLine(); public static void Main()
break; {
case 3: Console.WriteLine("\n Roots are Re Quadraticroots qr = new Quadraticroots();
al and Equal"); qr.read();
r1 = r2 = (-b) / (2 * a); qr.compute();
Console.WriteLine("\n First root “+r1); } }}
Console.WriteLine("\n Second root “+r2);
Console.ReadLine();
break;
case 4: Console.WriteLine("\n Roots are Im
aginary");
r1 = (-b) / (2 * a);
r2 = Math.Sqrt(-d1) / (2 * a);
Console.WriteLine("\n First root is “+r1+
• In C#, these data types are categorized based
on how they store their value in the memory.
C# includes following categories of data types:
• Value type
• Reference type
Value Type and a Reference Type
Value Type:

• A Value Type stores its contents in memory allocated on the stack.


• When you created a Value Type, a single space in memory is
allocated to store the value and that variable directly holds a value.
• If you assign it to another variable, the value is copied directly and
both variables work independently.
• Predefined datatypes, structures, enums are also value types, and
work in the same way.
• Value types can be created at compile time and Stored in stack
memory, because of this, Garbage collector can't access the stack.
• e.g. int x = 10;
• Here the value 10 is stored in an area of memory called the stack.
• value type

• When you pass a value type variable from one


method to another method, the system
creates a separate copy of a variable in
another method, so that if value got changed
in the one method won't affect on the
variable in another method.
static void ChangeValue(int x)
{ x = 200;
Console.WriteLine(x); }

static void Main(string[] args)


{ int i = 100; Console.WriteLine(i); ChangeValue(i);
Console.WriteLine(i);
}
• Output:
• 100
200
100
Reference Type:
• Reference Types are used by a reference which holds a reference
(address) to the object but not the object itself.
• Because reference types represent the address of the variable
rather than the data itself, assigning a reference variable to another
doesn't copy the data.
• Instead it creates a second copy of the reference, which refers to
the same location of the heap as the original value. Reference Type
variables are stored in a different area of memory called the heap.
• This means that when a reference type variable is no longer used, it
can be marked for garbage collection. Examples of reference types
are Classes, Objects, Arrays, Indexers, Interfaces etc.
• e.g.
• int[] iArray = new int[20];
• In the above code the space required for the 20 integers that
make up the array is allocated on the heap.
Reference Type
• Unlike value types, a reference type doesn't
store its value directly. Instead, it stores the
address where the value is being stored. In
other words, a reference type contains a
pointer to another memory location that
holds the data.
DIFFERENCE
Value Type Reference Type
• A Value Type holds the data • Reference Type contains a
within its own memory pointer to another memory
allocation location that holds the real
• Value Type variables are data.
stored in the stack. • Reference Type variables
• Example: Predefined are stored in the h
datatypes, structures, • Example: Classes, Objects,
enums Arrays, Indexers, Interfaces
etc.
var
Var variable in c#
• Local variables can be declared without giving an
explicit type.
• The var keyword instructs the compiler to infer
the type of the variable from the expression on
the right side of the initialization statement.
• The inferred type may be a built-in type, an
anonymous type, a user-defined type, or a type
defined in the .NET Framework class library.
// i is compiled as an int
var i = 5;

// s is compiled as a string
var s = "Hello";

// a is compiled as int[]
var a = new[] { 0, 1, 2 };

// list is compiled as List


<int> var list = new List<int>();
Characteristics of the var keyword
• The "var" keyword initializes variables with var
support. The data type of a var variable will be
determined when assigning values ​to
variables.
• Do not use var to declare the data type for the
property (properties) as well as the return
type of the method (method) in the class.
• Declare the array with the var keyword
C# boxing and unboxing
• C# Type System contains three Types , they are
Value Types , Reference Types and Pointer
Types.
• C# allows us to convert a Value Type to a
Reference Type, and back again to Value Types
.
• The operation of Converting a Value Type to a
Reference Type is called Boxing and the
reverse operation is called Unboxing.
C# | Boxing And Unboxing

• Boxing and unboxing is an important concept


in C#.
• C# Type System contains three data types:
• Value Types (int, char, etc),
• Reference Types (object)
• Basically it convert a Value Type to a Reference
Type, and vice versa. Boxing and Unboxing
enables a unified view of the type system in
which a value of any type can be treated as an
object.
Boxing In C#
• The process of Converting a Value Type (char, int
etc.) to a Reference Type(object) is called Boxing.
• Boxing is implicit conversion process in which
object type (super type) is used.
• The Value type is always stored in Stack. The
Referenced Type is stored in Heap.
• Example :
• int num = 23; // 23 will assigned to num Object
Obj = num; // Boxing
Boxing
// C# implementation to demonstrate System.Console.WriteLine
// the Boxing ("Value - type value of num is : “+ num);
using System; System.Console.WriteLine
class GFG { ("Object - type value of obj is : “+ obj);
}
// Main Method }
static public void Main() Run on IDE
{ Output:
Value - type value of num is : 100
// assigned int value Object - type value of obj is : 2020
// 2020 to num
int num = 2020;

// boxing
object obj = num;

// value of num to be change


num = 100;
Unboxing In C#

• The process of converting reference type into


the value type is known as Unboxing.
• It is explicit conversion process.
• Example :int num = 23; // value type is int and
assigned value 23 Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing
BOXING AND UNBOXING EXAMPLE
// C# implementation to demonstrate // unboxing
// the Unboxing int i = (int)obj;
using System;
class GFG { // Display result
Console.WriteLine("Value of ob
// Main Method object is : " + obj);
static public void Main() Console.WriteLine("Value of i is : " +
{ i);
}
// assigned int value }
// 23 to num Output:
int num = 23; Value of ob object is : 23
Value of i is : 23
// boxing
object obj = num;
Boxing
• 1: int Val = 1;
• 2: Object Obj = Val; //Boxing
• The first line we created a Value Type Val and
assigned a value to Val.
• The second line , we created an instance of
Object Obj and assign the value of Val to Obj.
From the above operation (Object Obj = i ) we
saw converting a value of a Value Type into a
value of a corresponding Reference Type .
• These types of operation is called Boxing.
UnBoxing
• 1: int Val = 1;
• 2: Object Obj = Val; //Boxing
• 3: int i = (int)Obj; //Unboxing
• The first two line shows how to Box a Value Type .
• The next line (int i = (int) Obj) shows extracts the Value Type from
the Object . That is converting a value of a Reference Type into a
value of a Value Type. This operation is called UnBoxing.
• Boxing and UnBoxing are computationally expensive processes.
When a value type is boxed, an entirely new object must be
allocated and constructed , also the cast required for UnBoxing is
also expensive computationally.

Das könnte Ihnen auch gefallen