0% found this document useful (0 votes)
54 views

.NET Programming Unit-1

This document outlines a 6-credit course on .NET programming. It is divided into 4 units that cover topics like OOP concepts in C#, inheritance and polymorphism, delegates and events, windows forms, and ADO.NET for data access. The document also provides background on the evolution of .NET and C# from older technologies like OLE and COM, and describes key aspects of the .NET framework like the Common Language Runtime.

Uploaded by

PALLAVI Y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

.NET Programming Unit-1

This document outlines a 6-credit course on .NET programming. It is divided into 4 units that cover topics like OOP concepts in C#, inheritance and polymorphism, delegates and events, windows forms, and ADO.NET for data access. The document also provides background on the evolution of .NET and C# from older technologies like OLE and COM, and describes key aspects of the .NET framework like the Common Language Runtime.

Uploaded by

PALLAVI Y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

.

NET PROGRAMMING
6 Credits

UNIT-I
Introduction: Overview of OOP, Introduction to C # - Characteristics, application, Difference
between c and c#, The .NET strategy, the origins of the .NET technology, the .NET framework,
benefits of the .NET approach, C# and .NET, c# program structure, command line argument, math
function, Literals, variables and data , constant variables, scope of variables, boxing and unboxing,
Operators in C#, expression, Decision making and looping statements in c# Methods in C# :
declaring methods, nesting of methods, methods parameters, the output parameters, variable
arguments list, method overloading, Arrays - variable size arrays, the system, array class, array list
class, String handling

UNIT-II
Inheritance and polymorphism: classical inheritance, containment inheritance, defining a
subclass, visibility control, defining subclass constructors, multilevel inheritance, hierarchical
inheritance, overriding methods, hiding methods, abstract classes, abstract methods, sealed classes,
Preventing inheritance, sealed methods, polymorphism. Interfaces: Multiple Inheritance: defining
an interface, extending an interface, implementing interface, interface & inheritance, explicit
interface implementation, abstract class and interface. Operator overloading: over loadable
operators, need for operator overloading, defining Operator overloading, overloading unary
operators, overloading binary operators, overloading Comparison operators.

UNIT-III
Delegates and Events: Delegate, delegate declaration, delegate methods, delegates instantiation,
delegate invocation, using delegates, multicast delegates, events. Managing Console I/O operations:
console class, console input, console output, formatted output, numeric formatting, standard
numeric format, custom numeric format. Managing Errors and Exceptions : Types of errors,
exceptions, syntax of exception handling code, multiple catch statement, the exception hierarchy,
general catch handler, using final statement, nested try blocks, throwing our own exceptions,
checked and unchecked operators, using exceptions for debugging.

UNIT-IV
Introducing windows forms: A tale of three GUI namespaces, overview of the system. Windows.
Forms Namespaces, Anatomy of a Form, Component class, control class, control. Programming
with windows forms controls: Working with button types, check boxes, Radio buttons, Group
boxes, list boxes, calendar control, assigning tooltips for controls. Data access with ADO.NET:
The need for ADO.NET, two faces of ADO.NET, role of ADO.NET data providers, Building a
simple test database, selecting a data provider, working with connected layer of ADO.NET &
OleDb Data reader, inserting, updating and deleting records using OleDb command.

Text Books:
1. Profession c# - By Karli Watson, Simon Robinson, Christian Nagel, Wiley India Pvt Ltd.
2. C# Unleashed – By Joseph Mayo, Techmedia, First Edition
3. Programming C# - By Jesse Liberty, Shroff Publishers, 4TH Edition
4. Programming In C# - By Barbara Doyle, Cengage \ Delmar Learning India Pvt.
EVOLUTION OF (.NET) C#

The number of WWW (World Wide Web) users increased. But users are not able to use WWW
efficiently, because of its limitations.
1. We can see only one site at a time.
2. The site has to be authored to our hardware environment.
3. The information we get is basically read-only.
4. We cannot compare dynamically similar information stored in different sites.
5. The internet is a collection of many information islands that do not cooperate with each other.
It continues to be a browsing and presentation network rather than an intelligent knowledge
management network.
Microsoft Chairman Bill Gates, the architect of many innovative software products, wanted to
develop a software platform that will overcome the limitations of WWW. The outcome is a new
generation platform called “.NET”.
.NET is simply Microsoft's vision of “Software as a service”.
The research and development work of the .NET platform started in the mid 90’s but officially
announced in 2000. C# language was also introduced, which was already used to code a few key
modules of the .NET platform.

About .NET and C#


.NET is a software framework that includes everything required for developing software for web
services. It integrates presentation technologies, component technologies, and data technologies
on a single platform so as to enable users to develop Internet applications easily.
.NET framework has many class libraries which were maintained by Simplified Managed C
(SMC). Anders Hejlsberg formed a team and developed a language called COOL (C like Object
Oriented Language). Due to some trademark reasons COOL was renamed as C#.

Microsoft .NET Strategy


The Microsoft .NET software solution strategy includes three key approaches:
1. Microsoft .NET Platform.
2. Microsoft .NET Products & Services.
3. Third Party .NET Services.

Microsoft .NET Platform includes components that help to develop a new generation of smart
internet services.
1. .NET Infrastructure and Tools.
2. .NET User Experience.
3. .NET Building Block.
4. .NET Device Software.

Microsoft .NET Product & Services consists of the services.


1. Windows .NET
2. MSN .NET
3. Office .NET
4. Visual Studio .NET
5. Personal Subscription Services
6. bCentral for .NET

Third Party .NET Services provides opportunities to a vast range of developers and users to
produce corporate and vertical services using .NET platform.

Origin of .NET Technology


The technology of .NET has gone through three significant phases of development.
1. OLE Technology.
2. COM Technology.
3. .NET Technology.
These developments took place during the 1990’s.

OLE Technology
OLE (Object Linking & Embedding) Technology was developed by Microsoft in the early
1990’s to enable easy interprocess communications.
OLE provided supports:
1. To embed documents from one application to another application.
2. To enable one application to manipulate objects located in another application.
These enabled users to develop applications which required Interoperability between various
products such as Ms Word, Ms Excel.

COM Technology
When programs become large and complex, the monolithic approach of developing software
creates many problems in terms of maintainability and testing of software. To overcome these
problems Microsoft introduced the component based model for developing software programs.
In component based approach a program is broken into a number of independent components
where each component offers a particular service. Each component can be developed and tested
independently and integrated into the main system. This technology is known as the Component
Object Model (COM) and the software built using COM is referred as Componentware.
The COM technology offers a number of advantages to developers and users:
1. It reduces the overall complexity of software development.
2. It enables distributed development across multiple organizations or departments.
3. It enhances the software maintainability.

.NET Technology
.NET technology is a third generation component model. This provides a new level of
interoperability compared to COM technology.
The COM provides a standard binary mechanism for inter module communication. This
mechanism is replaced by an intermediate language called Microsoft Intermediate Language
(MSIL) or IL in the .NET technology.
Various .NET language compilers enforce interoperability by compiling code into IL, which is
automatically compatible with other IL modules. The inherent characteristics of IL code is
metadata, which is data about data and describes its characteristics, including data types and
locations. IL allows for true cross language integration. In addition to IL, .NET includes
a host of other technologies and tools that will enable us to develop and implement web based
applications easily.

.NET Framework
.NET framework is one of the tools provided
by the .NET infrastructure and tools component of the .NET platform. C# derives
much of its power from the .NET framework
on which it runs..NET framework provides an environment for building, deploying and running
web services and other applications.
.NET framework consists of three technologies:
1. Common Language Runtime (CLR).
2. Framework Base Classes.
3. User & Program Interfaces (ASP.NET & Winforms).

The CLR is the core of the .NET framework and is responsible for loading and running C#
programs.
Base Classes provides basic data types, collection classes and other general classes for use by C#
and other .NET languages.
The top layer contains a set of classes for developing web services and to deal with the user
interface.

Common Language Runtime


CLR is the heart and soul of the .NET framework. It is a runtime environment in which programs
written in C# and other .NET languages are executed. It also supports cross language
interoperability.
The services provided by CLR:
1. Loading and execution of programs.
2. Memory isolation for applications.
3. Verification of type safety.
4. Compilation of IL into native executable code.
5. Provides metadata.
6. Memory management.
7. Enforcement of security.
8. Interoperability with other systems.
9. Managing exceptions & errors.
10. Provides support for debugging & profiling.

The major components of CLR:


1. Common Type System.
2. Intermedia Language (IL).
3. Execution Support Functions.
4. Security.
5. Garbage Collection.
6. Class Loader.
7. Memory Layout.

Flowchart of CLR activities for executing programs:


The source code is compiled to IL while the metadata engine creates metadata information. IL
and metadata are linked with other native code if required and the resultant IL code is saved.
During execution, the IL code and any requirement from the base class library are brought
together by the class loader. The combined code is tested for type-safety and then compiled by
the JIT compiler to produce native machine code, which is sent to the runtime manager for
execution.

Common Type System (CTS)


It is one of the components of CLR. .NET framework provides multiple language support using
the feature known as Common Type System.
The CTS supports a variety of types and operations found in most programming languages and
therefore calling one language from another does not require type conversions.
C# is specially designed for the .NET platform, but we can also build .NET programs in a
number of other languages like C++, Visual Basic.
Common Language Specification (CLS)
The CLS defines a set of rules that enables interoperability on the .NET platform. These rules
serve as a guide to third-party compiler designers and library builders.
The CLS is a subset of CTS and therefore the languages supporting the CLS can use each others’
class libraries.
Application Program Interfaces (APIs) that are designed by following the rules of CLS can easily
be used by all the .NET languages.

Microsoft Intermediate Language


MSIL or simply IL is an instruction set into which all the .NET programs are compiled. It is akin
to assembly language and contains instructions for loading, storing, initializing and calling
methods.
When we compile a C# program or any program written in a CLS-Compliant language, the
source code is compiled into MSIL.

Managed Code
CLR is responsible for managing the execution of code compiled for the .NET platform.
The code that satisfies the CLR at runtime in order to execute is referred to as managed code.
Compilers that are compatible to the .NET platform generate managed code.
Ex: C# compiler (and other compilers) generates managed code that is IL code. The IL code is
then converted to native machine code by the JIT compiler.

Framework Base Classes


.NET provides a library of base classes which are used to implement applications quickly. The
base classes can be used in programs by
● Simply instantiating them and invoking their methods.
● Inheriting them through derived classes, thus extending their functionalities.

Many base classes reside in the namespace System. These base classes can be used for many
different tasks:
1. Input/Output operations.
2. String Handling.
3. Managing arrays, lists, maps, etc.
4. Accessing files and file systems.
5. Accessing the registry.
6. Security.
7. Windowing.
8. Windows messages
9. Database Management.
10. Evaluation of mathematical functions.
11. Drawing.
12. Managing errors and exceptions.
13. Connecting to the Internet and many more.

User and Program Interface


.NET framework provides tools for managing user and application interfaces. The tools are:
1. Windows Forms.
2. Web Forms.
3. Console Applications.
4. Web Services.
These tools enable users to develop user friendly desktop based as well as web based
applications using a variety of languages on the .NET platform.

Visual Studio .NET (VS.NET)


VS.NET supports an Integrated Development Environment (IDE) with a rich set of features and
productivity tools. These features and tools allow developers to build web applications faster and
easier.
Using web services and XML regardless of the language chosen for development, there is only
one environment to learn, configure, and use. That means, we need not have to switch back and
forth between environments to build, debug, and deploy our code.

VS.NET provides tools that extend support to the development life cScheme

.NET Languages
The .NET framework is a language neutral. We can use a number of languages for developing
.NET applications. They are:
Native to .NET
1. C# (specially created for .NET)
2. C++
3. Visual Basic
4. JScript

Third-party Languages
1. COBOL
2. Eiffel
3. Perl
4. Python
5. SmallTalk
6. Mercury
7. Scheme

All .NET languages are not created equal. Some can use the components of other languages,
some can use the classes produced in other languages to create objects, and some languages can
extend the classes of other languages using inheritance features of .NET.

Benefits of the .Net approach


1. Simple and faster system development.
2. Rich object model.
3. Enhanced built in functionality.
4. Many different ways to communicate with the outside world.
5. Integration of different languages into one platform.
6. Easy deployment and execution.
7. Wide range of scalability.
8. Interoperability with existing applications.
9. Simple and easy to build sophisticated development tools.
10. Fewer bugs, and potentially better performance.

C# and .Net
C# is a new programming language introduced with .NET. It is a concise, elegant, .NET
language. With C# developers can quickly implement applications and components using the
built in capabilities of the .NET framework. Since the C# code is managed by the CLR it
becomes leaner
and safer than C++.

Overview of OOP
Object Oriented programming (OOP) is a programming paradigm that relies (based) on the
concept of classes and objects. It is used to structure a software program into simple, reusable
pieces of code blueprints (usually called classes), which are used to create individual instances of
objects. There are many object-oriented programming languages including JavaScript, C++,
Java, and Python.
Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.

Introduction to C#
C# is the only language designed specially for the .NET platform which provides tools and
services that fully exploit both computing and communications.
Unlike C++, Java and C# promote a one-stop coding approach to code maintenance. They group
classes, interfaces and implementations together in one file so that programmers can edit the
code more easily.
C# can be used to develop two kinds of programs:
● Executable application programs.
● Component Libraries.

Executable programs are written to carry out some tasks and require the method Main in one of
the classes.
Component Libraries do not require the Main method because they are not standalone
application programs. They are written for use by other applications. It is something similar to an
applet in Java.
Characteristics of C#
1. Simple:
C# was derived from C++, but pointers and many irksome operators of C++ like ->, :: used for
doing namespace, member access and reference are removed and single dot(.) operator is enough
in C#. Also C# provides boolean data types so that the compiler will caught usage of = sign in
place of == sign in the if statement. Many of such features makes C# more simpler than C++.

2. Consistent:
C# supports an unified type system which eliminates the problem of varying ranges of integer
types. All types are treated as objects and developer can extend the type system simply and
easily.

3. Modern:
C# is called modern language due to its support like Automatic garbage collection, modern
approach for error handling and debugging, Decimal datatype for financial applications, and
robust security model.
4. Object oriented:
C# is truly object oriented language, which supports encapsulation, inheritance, and
polymorphism. The entire C# class model is built on top of the Virtual Object System (VOS) of
the. NET framework. In C#, everything is an object so there are no global functions, variables,
and constants.

5. Type-safe:
Type safety promotes robust programs. Type safety measures are:
a. All dynamically allocated objects and arrays are initialized to zero.
b. Use of any uninitialized variables produces an error message by the compiler.
c. Access to arrays are range-checked and warned if it goes out of bounds.
d. C# does not permit unsafe casts.
e. C# enforces overflow checking in arithmetic operations.
f. Reference parameters that are passed are type-safe.
g. C# supports automatic garbage collection.

6. Versionable
Making new versions of software modules work with the existing applications is known as
versioning. C# provides support for versioning with the help of new and override keywords. This
support allows programmers to guarantee that their new class library will maintain binary
compatibility with the existing client applications.

7. Compatible
C# enforces the .NET common language specifications and therefore allows inter-operation with
other .NET languages. C#.provides support for transparent access to standard COM and OLE
Automation. It also permits inter-operation with C style APIs.

8. Flexible
C# does not support pointers, but still we may declare certain classes and methods as unsafe and
then use pointers to manipulate them. However these codes will not be type-safe.

9. Inter-operability
C# provides support for using COM objects, no matter what language was used to author them.
C# also supports a special feature that enables a program to call out any native API.

Applications of C#
1. Console Applications
2. Windows Applications
3. Developing Windows Controls
4. Developing ASP.NET projects
5. Creating Web Controls
6. Providing Web Services
7. Developing .Net component library

C# Program Structure - with simple program


A C# program consists of the following parts −
● Namespace declaration
● A class
● Class methods
● Class attributes
● A Main method
● Statements and Expressions
● Comments
Example 1:
class Exprogram1
{
public static void Main()
{
System.Console.WriteLine(“C# Programming”);
}
}

The first line is the class declaration, class is the keyword and Exprogram is the identifier that
specifies the name of the class to be defined.
Every C# executable programs must include the Main method in at least any one of the classes.
This method initiates the execution of the program. The keyword public is the access modifier or
specifier that tells the method is accessible by anyone. The keyword static declares the method is
global (accessible in the entire program) and it can be called without creating an instance of the
class (object). The compiler stores the address of the method as the entry point and uses this
information to begin execution before any objects are created. The keyword void tells the
method does not return any value.

After creating the source code, save it with .cs file extension. Ex: Exprogram.cs
For compiling the code: csc Exprogram.cs
The C# compiler compiles the code and creates an executable file (IL) named as Exprogram.
exe
For executing the code: Exprogram
Name of the program is sufficient, no need to use file extension.
System.Console.WhiteLine(“C# Programming”);
is the output statement, System is the namespace (scope) in which console class is located.
Namespace are the way C# segregates the .NET library classes into groups.
C# supports a feature known as using directive that can be used to import the namespace System
into the program. So that classes of that namespace can be used without namespace as prefix.
This is shown in Example 2.

Example 2:
using System;
class Exprogram1
{
public static void Main()
{
Console.WriteLine(“C# Programming”);
}
}

We can avoid the prefix System to the Console class by implementing the using System;
statement. Similarly we can avoid prefixing System.Console to the method WriteLine() by using
aliases for namespace classes. This takes the form:
using aliasname = classname;

Example 3:
using X= System.Console;
class Exprogram1
{
public static void Main()
{
X.WriteLine(“C# Programming”);
}
}

Adding Comment

Comment helps in maintenance of the program. It provides details regarding the implementation,
changes or updation history and the task performed by the program. The comments can be single
line or multiple line.

Example for single line comment

//program to add two numbers


Example for multiple line comment

/*program to swap two numbers by passing

reference parameters*/

Returning a value from Main


Yes, we can make the Main method to return a value. For this we have to include return
statement at the end of the Main method definition.

Example 4:
using System;
class Exprogram1
{
public static int Main()
{
Console.WriteLine(“C# Programming”);
return 0;
}
}
The program returns an integer type value to the system. This value serves as the program’s
termination status code. The purpose is to allow communication of success or failure to the
execution environment.

Command Line Arguments


The program behaves depending on the input value. The parameters are supplied to the Main
method at the time of invoking it for execution.

Example 5:
using System;
class Exprogram1
{
public static void Main(String []args)
{
Console.Write(“Hello”);
Console.WriteLine(“ ”+args[0]);
Console.Write(args[1]);
Console.Write(“ ”+args[2]);
}
}
Main is declared with a parameter args, which is an array of strings (known as string objects).
Any arguments provided in the command line (at the time of execution) are passed to the array as
its element. We can access the array elements as args[0], args[1], args[2], and so on.
The difference between WriteLine() and Write() is that, Write() method does not cause a line
break and therefore the next output statement is printed on the same line. WriteLine() method
causes a line break and therefore the next output statement is printed on the next new line.

The output statements concatenate strings using the + operator while printing.

Interactive C# Program

In the C# program, the values to string objects can be provided:

a. Using an assignment statement.


b. Through command line arguments.
c. And also possible through the keyboard at the time of execution.

Example 6:
using System;
class Exprogram1
{
public static void Main()
{
Console.Write(“What is your name?”);
string name = Console.ReadLine();
Console.Write(“Which course are you studying?”);
string course = Console.ReadLine();
Console.WriteLine(“Your name is ”+name);
Console.WriteLine(“Your course is ”+course);
}
}

Example 7: A program with two classes


using System;
class Expro1
{
public void display()
{
Console.WriteLine(“Hello”);
}
}

class Expro2
{
public static void Main()
{
Expro1 ob= new Expro1();
ob.display();
}
}

Multiple Main method


C# includes a feature that enables us to define more than one class with the Main method. Since
Main is the entry point for program execution, there are now more than one entry points. In fact,
there should be only one. This problem can be resolved by explicitly specifying which Main is to
be used to the compiler at the time of compilation as shown below.
csc filename.cs/main:classname

Example 8:
using System;
class Expro1
{
public static void Main()
{
Console.WriteLine(“Hello”);
}
}

class Expro2
{
public static void Main()
{
Console.WriteLine(“Hai”);
}
}

For the above program, we can mention like this


csc multipro.cs/main:Expro2

Token - It is the smallest non reducible, textual element in a program. There are five types of
token: Keywords, Identifiers, Literals, Operators, and Punctuations.

Keyword - Keywords are an essential part of a language. They have special meaning, predefined
meaning and they are reserved words. The C# keywords are:
Identifiers - Identifiers are programmer designed tokens. They are used for naming classes,
methods, variables, interfaces, namespace, literals, labels etc. The rules are

1. They can have alphabets, digits, and underscore.


2. They should not begin with digits.
3. Uppercase and lowercase letters are different.
4. Keywords can be used, but they should be prefixed with @

Ex: int @for; //valid

Literals - Literals are value constants assigned to variables in a program.

1. Integer Literals - An integer literal refers to a sequence of digits. There are two types of
integers, decimal integers and hexadecimal integers.
● Decimal integers: A sequence of digits 0 through 9. Ex: 23, 45, -853941
● Hexadecimal integers: A sequence of digits preceded by 0x or 0X. It also includes
alphabets A through F (a through f). Ex: 0x5, 0x6c, 0xd
2. Real Literals - These quantities are represented by numbers containing fractional parts.
Ex: 25.96f
3. Character Literals - A single character literal contains a single character enclosed within a
pair of single quote marks. Ex: 's'
4. String Literals - A string literal contains a sequence of characters enclosed within a pair
of double quote marks. Ex: "Program", "Hello World"
5. Boolean Literals - Boolean Literal values are true and false. They are used as values of
relational expression.
6. Backslash character Literals - They are used in output methods.

Constant Meaning

'\a' alert

'\b' backspace

'\f' form feed

'\n' new line

'\r' carriage return

'\t' horizontal tab

'\v' vertical tab

'\'' single quote

'\"' double quote

'\\' backslash

'\o' null

Operators - They are symbols used in expressions to describe operations involving one or more
operands.

Punctuators - They are symbols used for grouping and separating code. They are

● parentheses ()
● braces{}
● brackets []
● semicolon ;
● colon :
● comma ,
● period .

Variable is an identifier used to store data, denoting the location.

Data type specifies the size and the type of value that can be stored. C# datatypes are primarily
divided into two types

● Value type
● Reference type
● Pointer type is available for use only in unsafe code.
Value type

Value types which are of fixed length are stored on the stack. When a value of a variable is
assigned to another variable, the value is actually copied and two identical copies of the value are
available in memory.
● Predefined type: Integers, Real Numbers, Booleans, Characters
● User defined type: Enumerations, Structures

Integer type

Size and range of signed integer types

Type Size Minimum value Maximum value

sbyte 1byte -128 127

short 2bytes -32,768 32,767

int 4bytes -2,147,483,648 2,147,483,647

long 8bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Size and range of unsigned integer types

Type Size Minimum value Maximum value

byte 1byte 0 255

ushort 2bytes 0 65,535

uint 4bytes 0 4,294,967,295

ulong 8bytes 0 18,446,744,073,709,551,615


All integers are by default int type. In order to specify which of the other integer types the values
must take, we must append the characters U, L, or UL. Ex:

256 U

256 L

256 UL

Note: Lowercase u, l, or u is also allowed to use but it will confuse us with 1(one) and l.

Floating point type (real numbers)

● Float type: The float type values are single precision numbers with a precision of seven
digits.
● Double type: The double type values are double precision numbers with a precision of
15/16 digits.

Ex: float a=10.963f;

double r=457.963;

Type Size Minimum value Maximum value

float 4byte +- 1.5*10-45 +- 3.4*1038

double 8bytes +- 5.0*10-324 +- 1.7*10308

● Decimal type: It is the high precision, 128 bit data type that is designed for use in
financial and monetary calculations. The range is +-1.0*10-28 to +-7.9*1028 with 28
significant digits. Ex: decimal h=12509.45m;

Note: Floating point data type supports a value NaN (Not a Number). It is used to represent the
result of an operation such as division by zero.

Character type

The character type has a size of 2 bytes but in fact it can hold only a single character.

Ex: char s='K';

Boolean type

Boolean type is denoted by the keyword bool and uses only one bit of storage. It is used when we
want to test a condition during the execution of the program. There are only two values true or
false. Note: We cannot use 0 for false and 1 for true.

Ex: bool g= true;

Example 9:

bool student = true;

if (student == true)

Console.WriteLine("student");

else

Console.WriteLine("Not a student");

Reference type

Reference types which are of variable length are stored on the heap. When a reference variable is
assigned with another reference variable, only the reference is copied. This means, the actual
value remains in the same location and there will be two references to a single value.
● Predefined type: object type, string type
● User defined type: class, array, interface, delegates

Default values: In C#, the variable is either explicitly assigned a value or automatically
assigned a default value. Default value is not assigned to all variables, it will be automatically
assigned only for
1. Static variables
2. Instance variables
3. Array elements

Type Default value

All integer types 0

char type '\x000'

float type 0.0f

double type 0.0d

decimal type 0.0m

bool type false


Enum type 0

All reference type null

Constant variables
The variables whose values do not change during the execution of the program are known as
constants. The keyword const is used for declaration.
Ex: const int n=10;
Scope of variables
The scope of a variable is the region of code within which the variable can be accessed. The
different categories of variables are
1. Static Variables
2. Instance variables
3. Array elements
4. Value parameters
5. Reference parameters
6. Output parameters
7. Local variables
Example 10:
Example 11:
Static Members:
● The variables and methods declared with the keyword static are called static members.
● Static members are common to all the objects and accessed without using a particular
object.
● Static members belong to the whole class.
● The members are also referred to as class variables and class methods.

Constant Members:
● C# permits declaration of data fields of a class as constants using the keyword const.
● These members are implicitly static. Therefore only one copy of it is stored which is
common for all objects of the class.
● The value is assigned to members at compile time and it cannot be changed later.

public const int n=10;

Read-only members:

● Read-only members are constants whose values are decided at runtime.


● The keyword readonly is used.
● The members can have different constant values for different objects of the class.
● The values to the members are assigned using a constructor method, but it cannot be
changed later.

class program
{
public readonly int m;
public program(int x)
{
m=x;
}
…….
}
class test
{
public static void Main()
{
program o=new program(10);
program p=new program(25);
}
}

Boxing and Unboxing

In object oriented programming language, methods are invoked by only using objects. C#
enables us to use value type like int to call methods.

Boxing means the conversion of a value type on the stack to an object type on the heap.

Ex:
int a=15;
object ob=a; //creates box to hold a
The values are independent of each other.

Unboxing means the conversion of a object type on the heap to an value type on the stack. We
can only unbox a variable that has previously been boxed. Compiler checks that the value type
we request is actually stored in the object under conversion.

Ex:
int a=15;
object ob=a; //creates box to hold a
int b=(int)ob; // unbox on to int type

Operators in C#
1. Relational Operators
2. Arithmetic Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Conditional Operators
7. Increment and decrement Operators
8. Special Operators
Write your own examples for these statements

Arithmetic Expressions

Precedence of Arithmetic Operators

Type Conversions - Implicit Conversions and Explicit Conversions

Write your own examples

Operator Precedence and Associativity

Mathematical Functions

Decision Making and Branching Statements

1. Simple if statement
2. If else statement
3. Nested if or nested if else statement
4. Else if ladder
5. Switch statement
Write your own examples for these statements

Fallthrough in switch statement: In the absence of the break statement in a case block, the
control moves to the next case block without any problem. It is known as Fallthrough.

In C# it is not permitted to have Fallthrough, to make two or more case blocks to execute
we have to use goto statement.

Example 12:

switch(op)
{
case 1 : Console.WriteLine("Addition");
goto case 3;
case 2 : Console.WriteLine("Multiplication");
goto default;
case 3 : Console.WriteLine("Subtraction");
break;
default : Console.WriteLine("Division");
break;
}

? : Operator

Decision Making and Looping Statements

1. While statement
2. Do while statement
3. For statement
4. Foreach statement

Write your own examples for these statements

Jump statements (Jump in loop)

● break statement
● continue statement
● goto statement

Write your own examples for these statements

Methods in C#
Declaration of methods - Syntax:

modifier type methodname(parameter_list)

//body of the method

Invoking methods: The process of activating a method is known as invoking or calling. The
invoking is done using object and the dot operator. Syntax:

objectname.methodname(parameter_list);

Example 13:
using System;
class pro
{
int x=10, y=20;
public static void Main()
{
pro ob=new pro();
ob.sum(4,6); // method call
int p=ob.product(); //method call
Console.WriteLine(p);
}
public void sum(int a, int b)
{
Console.WriteLine(a+b);
}
int product()
{
int s=x*y;
return s; // returns the result
}
}

Nesting of methods

A method can be invoked using only it's name (without object and dot operator) by another
method of the same class. This is known as nesting of methods.

Example 14:
using System;
class prg
{
public static void Main()
{
prg s=new prg();
s.m1();
}
// nesting of method
void m1()
{
Console.WriteLine("sum");
m2(); //calling a method without object and dot operator
}
void m2()
{
Console.WriteLine("Difference");
}
}

Method Parameters: For managing the process of passing values and getting back the results,
C# employs four kinds of parameters - Value parameters, Reference parameters, Output
parameters, and Parameter arrays.

Pass by value

● The value of actual parameters are assigned to the corresponding formal parameters.
● Here, the method refer to only copies of those variables (in different memory location).
So changes made to the formal parameters will not affect corresponding actual
parameters.

Example 15:
using System;
class prg
{
public static void Main()
{
prg s=new prg();
int a =25;
s.m1(a);
Console.WriteLine(a); //value of a is 25
}
void m1(int b)
{
b=b+10;
Console.WriteLine(b); //value of b is 35
}
}

Pass by reference

● The reference of actual parameters are passed.


● The keyword ref should be used both in method definition and in method call.
● The reference parameters does not create new storage location. It represents the same
storage location as the actual parameters.

Note: The variables must be definitely assigned a value before it can be passed as reference
parameters.

Example 16:
using System;
class prg
{
public static void Main()
{
prg s=new prg();
int a =25;
Console.WriteLine(a); //value of a is 25
s.m1(ref a);
Console.WriteLine(a); //value of a is 35
}
void m1(ref int b)
{
b=b+10;
Console.WriteLine(b); //value of b is 35
}
}

Example 17:
Output parameter

● The output parameters are used to pass results back to the calling method.
● The keyword out should be used both in method definition and in method call.
● The output parameters does not create new storage location. It represents the same
storage location as the actual parameters.

Note: The variables should not be assigned with a value before it is passed as output parameters.

Example 18:
using System;
class prg
{
public static void Main()
{
prg s=new prg();
int a;
s.m1(out a);
Console.WriteLine(a); //value of a is 10
}
void m1(out int b)
{
b=10;
}
}

Example 19:

Variable Argument Lists (Parameter arrays)

● Variable Argument Lists means handling a variable number of arguments in methods.


● The keyword params should be used in method definition.
● The parameter arrays must be one dimensional arrays.
● In the formal parameter list the parameter arrays must be the last parameters.
Example 19:
using System;
class prg
{
public static void Main()
{
prg s=new prg();
int[] a= {5, 15, 20};
s.m1(a);
}
void m1(params int[] b)
{
foreach(int x in b)
{
Console.WriteLine(x);
}
}
}

Method Overloading

We can create more than one method with the same name, but with the different parameter list
and different definition. This is called method overloading. This is used when methods are
required to perform similar tasks but using different input parameters.

Example 20:
using System;
class prg
{
public static void Main()
{
prg s=new prg();
s.add(2, 3);
s.add(5, 10, 20);
}
void add(int x, int y)
{
Console.WriteLine(x+y);
}
void add(int p, int q, int r)
{
Console.WriteLine(p+q+r);
}
}

Array: Array is a collection of similar type of elements that share a common name. The types of
array are one dimensional arrays, two dimensional arrays, and multidimensional arrays.

Declaration of array: type[] arrayname;

Creation of array: arrayname = new type[size];

Both can be done together like,

type[] arrayname= new type[size];

Assign values

arrayname[subscript] = value;

One dimensional Arrays: Stores a list of values. Initialization Examples:

int [] n={1, 2, 3};

int [] m = new int[2];

m[0]=10;

m[1]=20;

int [] x = new int[4] {1, 2, 3, 4};

We can find the length of the array, using the variable named Length. Arrays are
class based and store the allocated size in a variable named Length.

arrayname.Length

Two dimensional arrays: Stores a table of values.

Declaration: type[,] arrayname;

Creation: arrayname = new type[size, size];

Assign values: arrayname[subscript, subscript]= value;

Examples:

int [,] n={{1, 2, 3},{4, 5, 6}};

int [,] m = new int[2, 2];


m[0, 0]=2;

m[0, 1]=4;

m[1, 0]=6;

m[1, 1]=8;

Variable-size arrays : It is also called jagged arrays. The two dimensional arrays will have
different lengths for each row.

int [][]m = new int[2][]; //two rows

m[0] = new int[2]; // first row with two columns(elements)

m[1]=new int[5]; // second row with five columns(elements)

Example 21:
using System;
class prg
{
public static void Main()
{
int[][] a=new int[2][];
a[0] = new int[3]{1, 2, 3};
a[1] = new int[5]{4, 2, 3, 6, 8};
foreach(int [] n in m)
{
foreach(int d in n)
Console.WriteLine(d);
}
}
}

Example 22:
System.Array class

Every array creation is automatically derived from the System.Array class. This class defines
many methods that can be used to manipulate arrays more efficiently. Like, Clear(), CopyTo(),
GetLength(), GetValue(), Length, SetValue(), Reverse(), Sort(), and many more.

Example 23:

using System;
class prg
{
public static void Main()
{
int[] a= {4, 2, 3, 6, 8};
int[] b= new int[10];
Array.Sort(a);
Array.Reverse(a);
Array.SetValue(2, 15);
Array.CopyTo(a,b);
for(int i=0; i<=b.Length; i++)
{
Console.WriteLine(i);
}
}
}

ArrayList Class

System.Collections namespace defines a class known as ArrayList that can store a dynamically
sized array of objects.

ArrayList arrayname = new ArrayList[size]; or ArrayList arrayname = new ArrayList[];

If size is not specified then it defaults to sixteen.

This class defines many methods that can be used to manipulate arrays more efficiently. Like,
Add(), Contains(), Clear(), CopyTo(), Insert(), Remove(), RemoveAt(), RemoveRange(), Sort(),
Capacity, Count and many more.

Example 24: Using ArrayList class methods.


Strings

A string is a sequence of characters. In C# strings can be created using string or String class and
StringBuilder class.

Using string class we can create string whose memory or size is static.

Ex1:

string s; //declaration

s="hello"; //initialization

Ex2:

string g=s; //assigning or copying

or

string g=string.Copy(s); //copying

Ex3:

string b="c#";

string c="program";

string a = b+c; //adding or concatenating

Or

string a = string.Concat(b,c);

Ex4:

string a = Console.ReadLine();

String objects are immutable, but there are many inbuilt methods that work with strings. Like,
Compare(), Concat(), Copy(), Equals(), Insert(), Join(), Remove(), and many more.

Example

using System;
class prg
{
public static void Main()
{
string s1= "C Sharp";
string s2= s1.Insert(9, "Programming");
string s3=string.Copy(s1);
Console.WriteLine(s2.Length);
Console.WriteLine(s2.ToUpper());
Console.WriteLine(s2.Trim());
}
}

Comparing strings: Comparison of two strings can be performed on different ways.

1. Using Compare() method we can do,

int m=string.Compare(a,b);

2. Using Equals() method we can do,

bool k=b.Equals(a);

or

bool k=string.Equals(a,b);

3. Using == operator we can do,

bool r=(a==b);

Here a and b are two string objects (variables).

Write a program to illustrate string comparison using any one way (or all).

Getting Substring

k="Programming";

i=2; j=6;

string s1= k.Substring(i); //output: s1=rogramming

string s2= k.Substring(i,j); //output: s2= rogra

Mutable strings can be created using StringBuilder class. This means StringBuilder class can
be used to create string whose memory or size is dynamic.

Declaration and Initialization

StringBuilder s1= new StringBuilder("program");


StringBuilder s2 = new StringBuilder();

StringBuilder class methods are Append(), Insert(), Remove(), Replace(), Length, Capacity,
Count and many more methods.

Example

using System;
class prg
{
public static void Main()
{
StringBuilder s= new StringBuilder("C Sharp");
s.Append(" Programming");
s.Insert(8,"!");
Console.WriteLine(s.Length);
Console.WriteLine(s.Capacity);
}
}

Array of strings

We can create a collection of strings using an array. Ex

string[] arrayname = new string[5];

string[] arrayname ={"Book", "Pen", "Pencil"};

Properties

We can use methods to set and get the value of a private data members. But it suffers from
drawbacks like, we have to code the method, user have to remember that they have to use
methods.

******

You might also like