.NET Programming Unit-1
.NET Programming Unit-1
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.
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.
Third Party .NET Services provides opportunities to a vast range of developers and users to
produce corporate and vertical services using .NET platform.
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.
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.
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.
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.
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
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.
reference parameters*/
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.
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
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);
}
}
class Expro2
{
public static void Main()
{
Expro1 ob= new Expro1();
ob.display();
}
}
Example 8:
using System;
class Expro1
{
public static void Main()
{
Console.WriteLine(“Hello”);
}
}
class Expro2
{
public static void Main()
{
Console.WriteLine(“Hai”);
}
}
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. 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
'\\' 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 .
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
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.
● 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.
double r=457.963;
● 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.
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.
Example 9:
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
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.
Read-only members:
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);
}
}
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
Mathematical Functions
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
1. While statement
2. Do while statement
3. For statement
4. Foreach statement
● break statement
● continue statement
● goto statement
Methods in C#
Declaration of methods - Syntax:
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
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:
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.
Assign values
arrayname[subscript] = value;
m[0]=10;
m[1]=20;
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
Examples:
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.
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.
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.
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:
or
Ex3:
string b="c#";
string c="program";
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());
}
}
int m=string.Compare(a,b);
bool k=b.Equals(a);
or
bool k=string.Equals(a,b);
bool r=(a==b);
Write a program to illustrate string comparison using any one way (or all).
Getting Substring
k="Programming";
i=2; j=6;
Mutable strings can be created using StringBuilder class. This means StringBuilder class can
be used to create string whose memory or size is dynamic.
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
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.
******