Introduction To C#(part )
Ms. Sudhriti Sengupta
&
Dr. Lavanya Sharma
Pure Object-Oriented Programming
Language
In C#, every thing is an object. There are no
more global functions, variable and constants.
It supports all three object oriented features:
• Encapsulation
• Inheritance
• Polymorphism
Type Safety
Type safety promotes robust programming.
Some examples of type safety are:
• All objects and arrays are initialized by zero
dynamically
• An error message will be produced, on use of
any uninitialized variable
• Automatic checking of array (out of bound and
etc.)
Compatible with other Language
C# enforces the .NET common language
specifications (CLS) and therefore allows
interoperation with other .NET language.
list of few important features of C#
• Boolean Conditions
• Automatic Garbage Collection
• Standard Library
• Assembly Versioning
• Properties and Events
• Delegates and Events Management
• Easy-to-use Generics
• Conditional Compilation
• Simple Multithreading
• LINQ and Lambda Expressions
• Integration with Windows
C# a widely used professional language
• It is a modern, general-purpose programming
language
• It is object oriented.
• 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.
Program Structure
A C# program consists of the following parts −
• Namespace declaration
• A class
• Class methods
• Class attributes
• A Main method
• Statements and Expressions
• Comments
using System;
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
statement Console.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.
Basic Syntax
C# is an object-oriented programming language.
In Object-Oriented Programming methodology,
a program consists of various objects that
interact with each other by means of actions.
The actions that an object may take are called
methods. Objects of the same kind are said to
have the same type or, are said to be in the
same class
Comments in C#
Comments are used for explaining code.
Compilers ignore the comment entries.
• The multiline comments in C# programs start
with /* and terminates with the characters */
• Single-line comments are indicated by the '//'
symbol
Identifiers
An identifier is a name used to identify a class, variable,
function, or any other user-defined item. The basic rules
for naming classes in C# are as follows −
• A name must begin with a letter that could be followed
by a sequence of letters, digits (0 - 9) or underscore.
The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol
such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and .
However, an underscore ( _ ) can be used.
• It should not be a C# keyword.
DATATYPES
Data types specify the type of data that a
valid C# variable can hold. C# is a strongly typed
programming language because in C#, each
type of data (such as integer, character, float,
and so forth) is predefined as part of the
programming language and all constants or
variables defined for a given program must be
described with one of the data types.
Data types in C# is mainly divided into three
categories
• Value Data Types
• Reference Data Types
• Pointer Data Type
Value Type
In C#, the Value Data Types will directly store the
variable value in memory and it will also accept
both signed and unsigned literals.
The derived class for these data types
are System.ValueType
The value types directly contain data. Some
examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers,
respectively. When you declare an int type, the
system allocates memory to store the value.
Different Value Data Types
• Signed & Unsigned Integral Types
• Floating Point Types
• Decimal Types
• Character Types
Signed & Unsigned Integral Types
There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in
signed or unsigned form.
ALIAS TYPE NAME TYPE SIZE(BITS) RANGE DEFAULT VALUE
sbyte System.Sbyte signed integer 8 -128 to 127 0
short System.Int16 signed integer 16 -32768 to 32767 0
Int System.Int32 signed integer 32 -231 to 231-1 0
long System.Int64 signed integer 64 -263 to 263-1 0L
byte System.byte unsigned integer 8 0 to 255 0
ushort System.UInt16 unsigned integer 16 0 to 65535 0
uint System.UInt32 unsigned integer 32 0 to 232 0
ulong System.UInt64 unsigned integer 64 0 to 263 0
Floating Point Types
There are 2 floating point data types which contain the
decimal point.
• Float: It is 32-bit single-precision floating point type. It
has 7 digit Precision. To initialize a float variable, use
the suffix f or F. Like, float x = 3.5F;. If the suffix F or f
will not use then it is treated as double.
• Double:It is 64-bit double-precision floating point
type. It has 14 – 15 digit Precision. To initialize a double
variable, use the suffix d or D. But it is not mandatory
to use suffix because by default floating data types are
the double type.
ALIAS TYPE NAME SIZE(BITS)
RANGE
(APROX)
DEFAULT
VALUE
float System.Single 32
3.4 × 1038 to
+3.4 × 1038 0.0F
double
System.Doubl
e
64
±5.0 × 10-
324 to ±1.7 ×
10308
0.0D
Decimal Types
The decimal type is a 128-bit data type suitable
for financial and monetary calculations. It has
28-29 digit Precision
ALIAS TYPE NAME SIZE(BITS)
RANGE
(APROX)
DEFAULT
VALUE
decimal
System.Deci
mal
128
-7.9 × 1028 to
7.9 × 1028 0.0M
Character Types
ALIAS TYPE NAME SIZE IN(BITS) RANGE
DEFAULT
VALUE
char System.Char 16
U +0000 to
U +ffff
‘0’
using System;
namespace ssg
{
class Program
{
static void Main(string[] args)
{
sbyte a = 126;
// sbyte is 8 bit
// singned value
Console.WriteLine(a);
a++;
Console.WriteLine(a);
// It overflows here because
// byte can hold values
// from -128 to 127
a++;
Console.WriteLine(a);
// Looping back within
// the range
a++;
Console.WriteLine(a);
Console.ReadKey();
}
}
}
Reference Type
The reference types do not contain the actual data
stored in a variable, but they contain a reference to the
variables.
The Reference Data Types will contain a memory
address of variable value because the reference types won’t
store the variable value directly in memory. The built-in
reference types are string, object.
In other words, they refer to a memory location. Using
multiple variables, the reference types can refer to a memory
location. If the data in the memory location is changed by one
of the variables, the other variable automatically reflects this
change in value. Example of built-in reference types
are: object, dynamic, and string.
String
It represents a sequence of Unicode
characters and its type name is System.String.
So, string and String are equivalent.
Example :
1) string s1 = "hello"; // creating through string keyword
2) String s2 = "welcome"; // creating through String class
Object
In C#, all types, predefined and user-defined,
reference types and value types, inherit directly
or indirectly from Object. So basically it is the
base class for all the data types in C#. Before
assigning values, it needs type conversion.
When a variable of a value type is converted to
object, it’s called boxing. When a variable of
type object is converted to a value type, it’s
called unboxing. Its type name is System.Object.
using System;
namespace ssg
{
class Program
{
static void Main(string[] args)
{
object obj;
obj = "ssg";
Console.WriteLine(obj);
// to show type of object
// using GetType()
Console.WriteLine(obj.GetType());
Console.ReadKey();
}
}
}
Pointer Type
Pointer type variables store the memory address of
another type. Pointers in C# have the same
capabilities as the pointers in C or C++. The Pointer
Data Types will contain a memory address of the
variable value. T o get the pointer details we have a
two symbols ampersand (&) and asterisk (*).
ampersand (&): It is Known as Address Operator. It
is used to determine the address of a variable.
asterisk (*): It also known as Indirection Operator. It
is used to access the value of an address.
using System;
class Program
{
static void Main(string[] args)
{
int Number1, Number2;
Console.WriteLine("please enter the Number1");
Number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("please enter the Number2");
Number2 = Convert.ToInt32(Console.ReadLine());
int Result;
Result = Number1 + Number2;
Console.WriteLine("Sum of two Numbers:" + Result.ToString());
Console.ReadLine();
}
}
C# Variables
A variable is a name given to a storage area
that is used to store values of various data types.
Each variable in C# needs to have a specific type,
which determines the size and layout of the
variable's memory.
For example, a variable can be of the type
String, which means that it will be used to store a
string value. Based on the data type, specific
operations can be carried out on the variable.
Arrays
An array is a group of like-typed variables
that are referred to by a common name. And each
data item is called an element of the array. The data
types of the elements may be any valid data type
like char, int, float etc. and the elements are stored
in a contiguous location.
Arrays are kind of objects, therefore it is easy
to find their size using the predefined functions.
The variables in the array are ordered and each has
an index beginning from 0. Arrays in C# work
differently than they do in C/C++.
Points to note
• In C#, all arrays are dynamically allocated.
• Since arrays are objects in C#, we can find
their length using member length. This is
different from C/C++ where we find length
using sizeof.
• A C# array variable can also be declared like
other variables with [] after the data type.
• The variables in the array are ordered and
each has an index beginning from 0.
• C# array is an object of base
type System.Array.
• Default values of numeric array and reference
type elements are set to be respectively zero
and null.
• A jagged array elements are reference types
and are initialized to null.
• Array elements can be of any type, including
an array type.
Syntax (Array)
< Data Type > [ ] < Name_Array >
Here,
< Data Type > : It define the element type of the
array.
[ ] : It define the size of the array.
< Name_Array > : It is the Name of array
• int[] x; // can store int values
• string[] s; // can store string values
• double[] d; // can store double values
• Student[] stud1; // can store instances of
Student class which is custom class
Only Declaration of an array doesn’t allocate
memory to the array. For that array must be
initialized
Array Initialization
type [ ] < Name_Array > = new < datatype > [size];
1) int[] intArray1 = new int[5];
Initialization of an Array after
Declaration
• // Intialization of array
str1 = new string[5]{ “Element 1”, “Element 2”,
“Element 3”, “Element 4”, “Element 5” };
• str2 = new string[]{ “Element 1”, “Element 2”,
“Element 3”, “Element 4”, “Element 5” };
WRONG
• // compile-time error: must give size of an
array
int[] intArray = new int[];
• // error : wrong initialization of an array
string[] str1
str1 = {“Element 1”, “Element 2”, “Element 3”,
“Element 4” };
Simple example of C# array, where we are going to declare, initialize
and traverse array.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Using For Each
• using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for ( int i = 0; i < 10; i++ ) {
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n ) {
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}
C# Array Types
There are 3 types of arrays in C# programming:
• Single Dimensional Array
• Multidimensional Array
• Jagged Array
C# Multidimensional Arrays
The multidimensional array is also known as
rectangular arrays in C#. It can be two
dimensional or three dimensional. The data is
stored in tabular form (row * column) which is
also known as matrix.
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr=new int[3,3];//declaration of 2D array
arr[0,1]=10;//initialization
arr[1,2]=20;
arr[2,0]=30;
//traversal
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
C# Jagged Arrays
In C#, jagged array is also known as "array of
arrays" because its elements are arrays. The
element size of jagged array can be different.
int[][] arr = new int[2][];
• With jagged arrays, we can store (efficiently)
many rows of varying lengths. No space (on
the tops of the skyscrapers) is wasted. Any
type of data—reference or value—can be
used.
• Jagged arrays have different performance
characteristics. Indexing jagged arrays is fast.
Allocating them is somewhat slow.
using System;
class Program
{
static void Main()
{
// Declare local jagged array with 3 rows.
int[][] jagged = new int[3][];
// Create a new array in the jagged array, and assign it.
jagged[0] = new int[2];
jagged[0][0] = 1;
jagged[0][1] = 2;
// Set second row, initialized to zero.
jagged[1] = new int[1];
// Set third row, using array initializer.
jagged[2] = new int[3] { 3, 4, 5 };
// Print out all elements in the jagged array.
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.Write(innerArray[a] + " ");
}
Console.WriteLine();
}
}
}
Array List
ArrayList represents an ordered collection of an
object that can be indexed individually. It is basically
an alternative to an array. It also allows dynamic
memory allocation, adding, searching and sorting
items in the list.
It can contain elements of any data types. It is
similar to an array, except that it grows
automatically as you add items in it. Unlike an array,
you don't need to specify the size of ArrayList.
Why C# ArrayList
C# array is a collection of data types. For example, you can
create an array for student marks. The marks are an integer
value so you can create an integer array that holds all student
marks. Suppose some students have marks from an
examination but other students have a grade. A grade is a
string value like “A”, ”B” and so on. What do you? You can
create two arrays, one for marks that is an integer array and
another for grade that is a string array. You have two arrays so
you can’t retrieve the result in students sequence because
you have marks in the first array then grades in the second
array. So when you have multiple types set then you can use
an ArrayList. ArrayList is one of the most flexible data
structures from C# Collections.
Array Vs ArrayList
• They are different object types. Arrays belong
to System.Array namespace whereas Arraylist
belongs to System.Collection namespaces .
• Array is strongly typed . This means that an array
can store only specific type of itemselements. As
a result, it is type safe, and is also the most
efficient, both in terms of memory and
performance. While in arraylist, we can store all
the datatype values.
• Array stores fixed number of elements. Size of an
Array must be specified at the time
of initialization . ArrayList grows automatically
and you don't need to specify size.
Properties of ArrayList
• Capacity: Gets or sets the number of elements that the
ArrayList can contain
• Count: Gets the number of elements actually
contained in the ArrayList.
COUNT vs. CAPACITY
Capacity is the number of the elements which the List can
store before resizing of List needed. But Count is the
number of the elements which are actually present in the
List.
Methods of ArrayList
• public virtual int Add(object value);
Adds an object to the end of the ArrayList.
• public virtual void Clear();
Removes all elements from the ArrayList.
• public virtual void Insert(int index, object
value);
Inserts an element into the ArrayList at the
specified index
• public virtual void Remove(object obj);
Removes the first occurrence of a specific object
from the ArrayList.
• public virtual void Reverse();
Reverses the order of the elements in the
ArrayList.
• public virtual void Sort();
Sorts the elements in the ArrayList.
using System;
using System.Collections;
class Program
{
static void Main()
{
//
// Create an ArrayList and add two ints.
//
ArrayList list = new ArrayList();
list.Add(5);
list.Add(7);
//
// Use ArrayList with method.
//
Example(list);
}
static void Example(ArrayList list)
{
foreach (int i in list)
{
Console.WriteLine(i);
}
}
}
using System;
using System.Collections;
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);
Console.WriteLine("Capacity: {0} ",l.Capacity);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write("{0} " ,i);
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
//Insert,Remove,RemoveRange,GetRange
using System;
using System.Collections;
class Program
{
static void Main()
{
//
// Create an ArrayList with three strings.
//
ArrayList list = new ArrayList();
list.Add("Amity");
list.Add("University");
list.Add("AIIT");
//
// Remove middle element in ArrayList.
//
//list.RemoveAt(1); // It becomes [Dot, Perls]
//
// Insert word at the beginning of ArrayList.
//
//list.Insert(0, "C#"); // It becomes [Carrot, Dot, Perls]
//
// Remove first two words from ArrayList.
//
//list.RemoveRange(0, 2);
//
// Display the result ArrayList.
//
foreach (string value in list)
{
Console.WriteLine(value);
}
/*ArrayList range = list.GetRange(2, 1);
// Display the elements.
//
Console.WriteLine("SECOND LIST");
foreach (string value in range)
{
Console.WriteLine(value); // bird, plant
}*/
}
}
STRING
A string is an object of type String whose value is
text. Internally, the text is stored as a sequential
read-only collection of Char objects. There is no
null-terminating character at the end of a C#
string; therefore a C# string can contain any
number of embedded null characters ('0').
The System.String data type represents a string in
.NET. A string class in C# is an object of type
System.String. The String class in C# represents a
string.
// String of characters
System.String authorName = “S Sengupta";
// String made of an Integer
System.String roll = "33";
// String made of a double
System.String numberString = "33.23";
String Class
String class defined in the .NET base class library represents
text as a series of Unicode characters. The String class
provides methods and properties to work with strings.
The String class has methods to clone a string, compare
strings, concatenate strings, and copy strings.
This class also provides methods to find a substring in a string,
find the index of a character or substring, replace characters,
split a string, trim a string, and add padding to a string.
The string class also provides methods to convert a string's
characters to uppercase or lowercase.
Create a string
• Create a string from a literal
string firstName;
firstName = “ssg";
• Create a string using concatenation
Sting concatenation operator (+) can be used to
combine more than one string to create a single
string.
string firstName = “XYZ";
string lastName = “ABC";
string authorDetails = firstName + " " + lastNam
e + " is a faculty”;
Console.WriteLine(authorDetails);
• Create a string using a property or a method
Some properties and methods of the String class
returns a string object such as SubString method
Get first n characters substring from a string in
C#
string Fname = “DNM is an AP of AUUP.";
string occ = Fname.Substring(0,3);
Console.WriteLine("Occupation: " + occ);
Console.ReadKey();
Get a substring with a start and end index
string str = “DNM is an AP of AUUP.";
int startIndex = 7;
int endIndex = str.Length - 7;
string title = str.Substring(startIndex, endIndex);
Console.WriteLine(title);
Console.ReadKey();
Find occurrence of substrings in a string in C#
string s1= “DNM is an AP of AUUP.”;
int f = s1.IndexOf(“DNM");
Console.WriteLine(f);
Console.Read();
[If no substring is found then -1]
Get a substring after or before a character in C#
string s1= "SSG is an AP of AUUP.";
int f = s1.IndexOf("AP");
string stringBeforeChar = s1.Substring(0, f );
Console.WriteLine(f);
Console.Read();
C# Replace() Method
String str = "I am a very good students";
Console.WriteLine("OldString {0} " , str);
Console.WriteLine("NewString: {0}" , str.Replace("very", "less"));
Console.ReadKey();
Retrival Vital Information
• static void Main()
• {
• string[] info = { "Name: Mobita Nobi", "Title: Mr.",
• "Age: 06", "Location: Tokyo", "Gender: M"};
• int found = 0;
• Console.WriteLine("The initial values in the array are:");
• foreach (string s in info)
• Console.WriteLine(s);
• Console.WriteLine("nWe want to retrieve only the key information. That is:");
• foreach (string s in info)
• {
• found = s.IndexOf(": ");
• Console.WriteLine(found);
• Console.WriteLine(" {0}", s.Substring(found ));
• }
Class and Object
Class and Object are the basic concepts of
Object Oriented Programming which revolve
around the real-life entities. A class is a user-
defined blueprint or prototype from which
objects are created. Basically, a class combines
the fields and methods(member function which
defines actions) into a single unit. In C#, classes
support the polymorphism, inheritance and also
provide the concept of derived classes and base
classes.
Objects
• It is a basic unit of Object Oriented Programming and
represents the real-life entities. A typical C# program
creates many objects, which as you know, interact by
invoking methods. An object consists of :
• State: It is represented by attributes of an object. It
also reflects the properties of an object.
• Behavior: It is represented by methods of an object. It
also reflects the response of an object with other
objects.
• Identity: It gives a unique name to an object and
enables one object to interact with other objects.
Consider Dog as an object and see the below
diagram for its identity, state, and behavior.
Objects correspond to things found in the real
world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online
shopping system might have objects such as
“shopping cart”, “customer”, and “product”.
C# program that uses class
class Box
{
public void Open()
{
System.Console.WriteLine("Box opened");
}
}
class Program
{
static void Main()
{
// The program begins here.
// ... Create a new Box and call Open on it.
Box box = new Box();
box.Open();
}
}

C#

  • 1.
    Introduction To C#(part) Ms. Sudhriti Sengupta & Dr. Lavanya Sharma
  • 2.
    Pure Object-Oriented Programming Language InC#, every thing is an object. There are no more global functions, variable and constants. It supports all three object oriented features: • Encapsulation • Inheritance • Polymorphism
  • 3.
    Type Safety Type safetypromotes robust programming. Some examples of type safety are: • All objects and arrays are initialized by zero dynamically • An error message will be produced, on use of any uninitialized variable • Automatic checking of array (out of bound and etc.)
  • 4.
    Compatible with otherLanguage C# enforces the .NET common language specifications (CLS) and therefore allows interoperation with other .NET language.
  • 5.
    list of fewimportant features of C# • Boolean Conditions • Automatic Garbage Collection • Standard Library • Assembly Versioning • Properties and Events • Delegates and Events Management • Easy-to-use Generics • Conditional Compilation • Simple Multithreading • LINQ and Lambda Expressions • Integration with Windows
  • 6.
    C# a widelyused professional language • It is a modern, general-purpose programming language • It is object oriented. • 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.
  • 7.
    Program Structure A C#program consists of the following parts − • Namespace declaration • A class • Class methods • Class attributes • A Main method • Statements and Expressions • Comments
  • 8.
    using System; class HelloWorld { staticvoid Main(string[] args) { /* my first program in C# */ Console.WriteLine("Hello World"); Console.ReadKey(); } }
  • 9.
    • The firstline 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.
  • 10.
    • The nextline 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 statement Console.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.
  • 11.
    Basic Syntax C# isan object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class
  • 12.
    Comments in C# Commentsare used for explaining code. Compilers ignore the comment entries. • The multiline comments in C# programs start with /* and terminates with the characters */ • Single-line comments are indicated by the '//' symbol
  • 13.
    Identifiers An identifier isa name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows − • A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit. • It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and . However, an underscore ( _ ) can be used. • It should not be a C# keyword.
  • 14.
    DATATYPES Data types specifythe type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.
  • 15.
    Data types inC# is mainly divided into three categories • Value Data Types • Reference Data Types • Pointer Data Type
  • 16.
    Value Type In C#,the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.
  • 17.
    Different Value DataTypes • Signed & Unsigned Integral Types • Floating Point Types • Decimal Types • Character Types
  • 18.
    Signed & UnsignedIntegral Types There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form. ALIAS TYPE NAME TYPE SIZE(BITS) RANGE DEFAULT VALUE sbyte System.Sbyte signed integer 8 -128 to 127 0 short System.Int16 signed integer 16 -32768 to 32767 0 Int System.Int32 signed integer 32 -231 to 231-1 0 long System.Int64 signed integer 64 -263 to 263-1 0L byte System.byte unsigned integer 8 0 to 255 0 ushort System.UInt16 unsigned integer 16 0 to 65535 0 uint System.UInt32 unsigned integer 32 0 to 232 0 ulong System.UInt64 unsigned integer 64 0 to 263 0
  • 19.
    Floating Point Types Thereare 2 floating point data types which contain the decimal point. • Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double. • Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.
  • 20.
    ALIAS TYPE NAMESIZE(BITS) RANGE (APROX) DEFAULT VALUE float System.Single 32 3.4 × 1038 to +3.4 × 1038 0.0F double System.Doubl e 64 ±5.0 × 10- 324 to ±1.7 × 10308 0.0D
  • 21.
    Decimal Types The decimaltype is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision ALIAS TYPE NAME SIZE(BITS) RANGE (APROX) DEFAULT VALUE decimal System.Deci mal 128 -7.9 × 1028 to 7.9 × 1028 0.0M
  • 22.
    Character Types ALIAS TYPENAME SIZE IN(BITS) RANGE DEFAULT VALUE char System.Char 16 U +0000 to U +ffff ‘0’
  • 23.
    using System; namespace ssg { classProgram { static void Main(string[] args) { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); Console.ReadKey(); } } }
  • 24.
    Reference Type The referencetypes do not contain the actual data stored in a variable, but they contain a reference to the variables. The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.
  • 25.
    String It represents asequence of Unicode characters and its type name is System.String. So, string and String are equivalent. Example : 1) string s1 = "hello"; // creating through string keyword 2) String s2 = "welcome"; // creating through String class
  • 26.
    Object In C#, alltypes, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object.
  • 27.
    using System; namespace ssg { classProgram { static void Main(string[] args) { object obj; obj = "ssg"; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); Console.ReadKey(); } } }
  • 28.
    Pointer Type Pointer typevariables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++. The Pointer Data Types will contain a memory address of the variable value. T o get the pointer details we have a two symbols ampersand (&) and asterisk (*). ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable. asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
  • 29.
    using System; class Program { staticvoid Main(string[] args) { int Number1, Number2; Console.WriteLine("please enter the Number1"); Number1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("please enter the Number2"); Number2 = Convert.ToInt32(Console.ReadLine()); int Result; Result = Number1 + Number2; Console.WriteLine("Sum of two Numbers:" + Result.ToString()); Console.ReadLine(); } }
  • 30.
    C# Variables A variableis a name given to a storage area that is used to store values of various data types. Each variable in C# needs to have a specific type, which determines the size and layout of the variable's memory. For example, a variable can be of the type String, which means that it will be used to store a string value. Based on the data type, specific operations can be carried out on the variable.
  • 31.
    Arrays An array isa group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location. Arrays are kind of objects, therefore it is easy to find their size using the predefined functions. The variables in the array are ordered and each has an index beginning from 0. Arrays in C# work differently than they do in C/C++.
  • 32.
    Points to note •In C#, all arrays are dynamically allocated. • Since arrays are objects in C#, we can find their length using member length. This is different from C/C++ where we find length using sizeof. • A C# array variable can also be declared like other variables with [] after the data type. • The variables in the array are ordered and each has an index beginning from 0.
  • 33.
    • C# arrayis an object of base type System.Array. • Default values of numeric array and reference type elements are set to be respectively zero and null. • A jagged array elements are reference types and are initialized to null. • Array elements can be of any type, including an array type.
  • 34.
    Syntax (Array) < DataType > [ ] < Name_Array > Here, < Data Type > : It define the element type of the array. [ ] : It define the size of the array. < Name_Array > : It is the Name of array
  • 35.
    • int[] x;// can store int values • string[] s; // can store string values • double[] d; // can store double values • Student[] stud1; // can store instances of Student class which is custom class Only Declaration of an array doesn’t allocate memory to the array. For that array must be initialized
  • 36.
    Array Initialization type [] < Name_Array > = new < datatype > [size]; 1) int[] intArray1 = new int[5];
  • 37.
    Initialization of anArray after Declaration • // Intialization of array str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” }; • str2 = new string[]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };
  • 38.
    WRONG • // compile-timeerror: must give size of an array int[] intArray = new int[]; • // error : wrong initialization of an array string[] str1 str1 = {“Element 1”, “Element 2”, “Element 3”, “Element 4” };
  • 39.
    Simple example ofC# array, where we are going to declare, initialize and traverse array. using System; public class ArrayExample { public static void Main(string[] args) { int[] arr = new int[5];//creating array arr[0] = 10;//initializing array arr[2] = 20; arr[4] = 30; //traversing array for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } } }
  • 40.
    Using For Each •using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ /* initialize elements of array n */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* output each array element's value */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); } Console.ReadKey(); } } }
  • 41.
    C# Array Types Thereare 3 types of arrays in C# programming: • Single Dimensional Array • Multidimensional Array • Jagged Array
  • 42.
    C# Multidimensional Arrays Themultidimensional array is also known as rectangular arrays in C#. It can be two dimensional or three dimensional. The data is stored in tabular form (row * column) which is also known as matrix. int[,] arr=new int[3,3];//declaration of 2D array int[,,] arr=new int[3,3,3];//declaration of 3D array
  • 43.
    using System; public classMultiArrayExample { public static void Main(string[] args) { int[,] arr=new int[3,3];//declaration of 2D array arr[0,1]=10;//initialization arr[1,2]=20; arr[2,0]=30; //traversal for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ Console.Write(arr[i,j]+" "); } Console.WriteLine();//new line at each row } } }
  • 44.
    C# Jagged Arrays InC#, jagged array is also known as "array of arrays" because its elements are arrays. The element size of jagged array can be different. int[][] arr = new int[2][];
  • 45.
    • With jaggedarrays, we can store (efficiently) many rows of varying lengths. No space (on the tops of the skyscrapers) is wasted. Any type of data—reference or value—can be used. • Jagged arrays have different performance characteristics. Indexing jagged arrays is fast. Allocating them is somewhat slow.
  • 46.
    using System; class Program { staticvoid Main() { // Declare local jagged array with 3 rows. int[][] jagged = new int[3][]; // Create a new array in the jagged array, and assign it. jagged[0] = new int[2]; jagged[0][0] = 1; jagged[0][1] = 2; // Set second row, initialized to zero. jagged[1] = new int[1]; // Set third row, using array initializer. jagged[2] = new int[3] { 3, 4, 5 }; // Print out all elements in the jagged array. for (int i = 0; i < jagged.Length; i++) { int[] innerArray = jagged[i]; for (int a = 0; a < innerArray.Length; a++) { Console.Write(innerArray[a] + " "); } Console.WriteLine(); } } }
  • 47.
    Array List ArrayList representsan ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. It can contain elements of any data types. It is similar to an array, except that it grows automatically as you add items in it. Unlike an array, you don't need to specify the size of ArrayList.
  • 48.
    Why C# ArrayList C#array is a collection of data types. For example, you can create an array for student marks. The marks are an integer value so you can create an integer array that holds all student marks. Suppose some students have marks from an examination but other students have a grade. A grade is a string value like “A”, ”B” and so on. What do you? You can create two arrays, one for marks that is an integer array and another for grade that is a string array. You have two arrays so you can’t retrieve the result in students sequence because you have marks in the first array then grades in the second array. So when you have multiple types set then you can use an ArrayList. ArrayList is one of the most flexible data structures from C# Collections.
  • 49.
    Array Vs ArrayList •They are different object types. Arrays belong to System.Array namespace whereas Arraylist belongs to System.Collection namespaces . • Array is strongly typed . This means that an array can store only specific type of itemselements. As a result, it is type safe, and is also the most efficient, both in terms of memory and performance. While in arraylist, we can store all the datatype values. • Array stores fixed number of elements. Size of an Array must be specified at the time of initialization . ArrayList grows automatically and you don't need to specify size.
  • 50.
    Properties of ArrayList •Capacity: Gets or sets the number of elements that the ArrayList can contain • Count: Gets the number of elements actually contained in the ArrayList. COUNT vs. CAPACITY Capacity is the number of the elements which the List can store before resizing of List needed. But Count is the number of the elements which are actually present in the List. Methods of ArrayList • public virtual int Add(object value); Adds an object to the end of the ArrayList.
  • 51.
    • public virtualvoid Clear(); Removes all elements from the ArrayList. • public virtual void Insert(int index, object value); Inserts an element into the ArrayList at the specified index • public virtual void Remove(object obj); Removes the first occurrence of a specific object from the ArrayList.
  • 52.
    • public virtualvoid Reverse(); Reverses the order of the elements in the ArrayList. • public virtual void Sort(); Sorts the elements in the ArrayList.
  • 53.
    using System; using System.Collections; classProgram { static void Main() { // // Create an ArrayList and add two ints. // ArrayList list = new ArrayList(); list.Add(5); list.Add(7); // // Use ArrayList with method. // Example(list); } static void Example(ArrayList list) { foreach (int i in list) { Console.WriteLine(i); } } }
  • 54.
    using System; using System.Collections; namespaceConsoleApp9 { class Program { static void Main(string[] args) { ArrayList al = new ArrayList(); Console.WriteLine("Adding some numbers:"); al.Add(45); al.Add(78); al.Add(33); al.Add(56); al.Add(12); al.Add(23); al.Add(9); Console.WriteLine("Capacity: {0} ",l.Capacity); Console.WriteLine("Count: {0}", al.Count); Console.Write("Content: "); foreach (int i in al) { Console.Write("{0} " ,i); } Console.WriteLine(); Console.Write("Sorted Content: "); al.Sort(); foreach (int i in al) { Console.Write(i + " "); } Console.WriteLine(); Console.ReadKey(); } }
  • 55.
    //Insert,Remove,RemoveRange,GetRange using System; using System.Collections; classProgram { static void Main() { // // Create an ArrayList with three strings. // ArrayList list = new ArrayList(); list.Add("Amity"); list.Add("University"); list.Add("AIIT"); // // Remove middle element in ArrayList. // //list.RemoveAt(1); // It becomes [Dot, Perls] // // Insert word at the beginning of ArrayList. // //list.Insert(0, "C#"); // It becomes [Carrot, Dot, Perls] // // Remove first two words from ArrayList. // //list.RemoveRange(0, 2); // // Display the result ArrayList. // foreach (string value in list) { Console.WriteLine(value); } /*ArrayList range = list.GetRange(2, 1); // Display the elements. // Console.WriteLine("SECOND LIST"); foreach (string value in range) { Console.WriteLine(value); // bird, plant }*/ } }
  • 56.
    STRING A string isan object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('0').
  • 57.
    The System.String datatype represents a string in .NET. A string class in C# is an object of type System.String. The String class in C# represents a string. // String of characters System.String authorName = “S Sengupta"; // String made of an Integer System.String roll = "33"; // String made of a double System.String numberString = "33.23";
  • 58.
    String Class String classdefined in the .NET base class library represents text as a series of Unicode characters. The String class provides methods and properties to work with strings. The String class has methods to clone a string, compare strings, concatenate strings, and copy strings. This class also provides methods to find a substring in a string, find the index of a character or substring, replace characters, split a string, trim a string, and add padding to a string. The string class also provides methods to convert a string's characters to uppercase or lowercase.
  • 59.
    Create a string •Create a string from a literal string firstName; firstName = “ssg";
  • 60.
    • Create astring using concatenation Sting concatenation operator (+) can be used to combine more than one string to create a single string. string firstName = “XYZ"; string lastName = “ABC"; string authorDetails = firstName + " " + lastNam e + " is a faculty”; Console.WriteLine(authorDetails);
  • 61.
    • Create astring using a property or a method Some properties and methods of the String class returns a string object such as SubString method Get first n characters substring from a string in C# string Fname = “DNM is an AP of AUUP."; string occ = Fname.Substring(0,3); Console.WriteLine("Occupation: " + occ); Console.ReadKey();
  • 62.
    Get a substringwith a start and end index string str = “DNM is an AP of AUUP."; int startIndex = 7; int endIndex = str.Length - 7; string title = str.Substring(startIndex, endIndex); Console.WriteLine(title); Console.ReadKey(); Find occurrence of substrings in a string in C# string s1= “DNM is an AP of AUUP.”; int f = s1.IndexOf(“DNM"); Console.WriteLine(f); Console.Read(); [If no substring is found then -1]
  • 63.
    Get a substringafter or before a character in C# string s1= "SSG is an AP of AUUP."; int f = s1.IndexOf("AP"); string stringBeforeChar = s1.Substring(0, f ); Console.WriteLine(f); Console.Read(); C# Replace() Method String str = "I am a very good students"; Console.WriteLine("OldString {0} " , str); Console.WriteLine("NewString: {0}" , str.Replace("very", "less")); Console.ReadKey();
  • 64.
    Retrival Vital Information •static void Main() • { • string[] info = { "Name: Mobita Nobi", "Title: Mr.", • "Age: 06", "Location: Tokyo", "Gender: M"}; • int found = 0; • Console.WriteLine("The initial values in the array are:"); • foreach (string s in info) • Console.WriteLine(s); • Console.WriteLine("nWe want to retrieve only the key information. That is:"); • foreach (string s in info) • { • found = s.IndexOf(": "); • Console.WriteLine(found); • Console.WriteLine(" {0}", s.Substring(found )); • }
  • 65.
    Class and Object Classand Object are the basic concepts of Object Oriented Programming which revolve around the real-life entities. A class is a user- defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support the polymorphism, inheritance and also provide the concept of derived classes and base classes.
  • 66.
    Objects • It isa basic unit of Object Oriented Programming and represents the real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. An object consists of : • State: It is represented by attributes of an object. It also reflects the properties of an object. • Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects. • Identity: It gives a unique name to an object and enables one object to interact with other objects.
  • 67.
    Consider Dog asan object and see the below diagram for its identity, state, and behavior. Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.
  • 68.
    C# program thatuses class class Box { public void Open() { System.Console.WriteLine("Box opened"); } } class Program { static void Main() { // The program begins here. // ... Create a new Box and call Open on it. Box box = new Box(); box.Open(); } }