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

Introduction to C#

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

Introduction to C#

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

Introduction to C#: identifiers, keywords, data types, variables,

constants, operators, precedence, associativity, type conversion,


decision and loop statements, generics, enumerations,
namespaces. Object Oriented Programming: encapsulation,
inheritance, polymorphism, abstraction, interfaces.

❖​INTRODUCTION TO C#
❖​IDENTIFIERS & KEYWORDS:
●​ An identifier is a sequence of chars used to identify a variable,
const or any user-defined programming elements.
●​ An identifier starts with a letter or underscore & ends with a char.
●​ C# identifier are ‘case sensitive’.
●​ MS suggests to use Hungarian & Camel Back notations. (it
represents an identifier in initial lower case letter followed by initial
capital letter for the subsequent words in the identifier, for ex ,
Myfirstprogram) .
●​ An identifier must not be a reserved word & should not have any
blank spaces.
●​ Keywords:

●​
❖​DATA TYPE VARIABLES & CONSTANT:
●​ C # support a rich varied selection of data type from built-in types.
→ints, strings to user-define types. →enumeration, structs &
classes.
●​ C# variables are categorized into 3 simple organization structs.
1.​ Value type, 2.Ref type, 3.Point type.
1.​ Value type: allows u to store the dat directly into the variables.
-​ They are derived from System. Value type.
-​ The value types & their content are stored at the same location in
memory.
-​ The default values of value types are stored on stack.
-​ Bool, byte(8-bit), char(16-bit), decimal(128-bit), double(64-bit),
float(32-bit), int(32-bit), long(64-bit), S byte(8-bit), short(16-bit),
uint(32-bit), u long(64-bit), u short(16-bit).
-​ Value type are divided into the following categories. a. Struct type,
b. Enum type.
▪​ Struct type: are a special form of objects having the properties of
value types. Value types are stored on the stack. Struct type are
also stored on stack.
▪​ The struct type encapsulate small group of related variables,
→name, roll no, age, class name. (they can contain constructors,
methods, properties, operators, events, nested types, indexes,
consts & field
Public structs student
{
String nm;
Int rno;
Int class nm;
.......\\methods
.......\\properties
}
●​ The structure type are divided into 5 catogories.
1.​ Integral type. 2. Floating type. 3. Decimal type. 4. Boolean type. 5.
Nullable type.
1.​ Integral type: consist of s byte, byte, short, u short, int. Uint,
long; u long & char. They are divided into two type Signed &
unsigned: unlike C++, conversion b\w 2 type requests explicit cast.
2.​ Floating-point-type: divided into 2 types single & double.
o​ Single float hold values upto 1.5×10-45 to 3.4×1038 with a precision
of 7 digits.
o​ Double hold values upto 5.0×10-324 to 1.7×10308 with a precision of
15-16 digits.
3.​ Decimal type: equivalent to lang int that behaves as if it is a
floating point no. As compared to floating point type, decimal type
has more precisions & smaller range.
4.​ Boolean type: simple true or false values.
o​ They can not be assigned to any other type, nor can they be used
in any sort of computation .
o​ The resources of express in C# is not a boolean express, unless u
specifically assign it as true or false.
o​ Int x=3;
If (x) { } \\ not work in C#
If (x!=0) { }\\valid
5.​ Nullable type: a PL supports nullable data types when dealing with
DBS or when a user does not want to assign a value to a variable
type. Type max & min. Cs

PROGRAM:
class type max & min
{
Static void main (string [ ] args)
Console.Writeline(“System minimums\n”);
Console.Writeline(“Min SByte:{0}”,System.SByte. MinValue);
Console.Writeline(“Min Byte:{0}”, System. Byte. MinValue);
Console.Writeline(“Min Decimal:{0}”,System.Decimal. MinValue);
Console.Writeline(“Min Int16:{0}”,System.Int16. MinValue);
Console.Writeline(“System maximus\n”);
Console.Writeline(“Max SByte:{0}”,System.SByte. MaxValue);
Console.Writeline(“Max Byte:{0}”,System.Byte. MaxValue);
Console.Writeline(“Max Int32:{0}”,System.Int32. MaxValue);
Console.Writeline(“Max Int64:{0}”,System.Int64. MaxValue);
Console.Writeline(“Max UInt64:{0}”,System.UInt64. MaxValue);
Console.Writeline(“Max Char:{0}”,System.Char. MaxValue);
Console.Writeline(“Max Single:{0}”,System.Single. MaxValue);
Console.Writeline(“Max Decimal:{0}”,System.Decimal. MaxValue);
Console.ReadLine();
}}
▪​ Enumeration type: user-defined integer data type that are declared
using enum keywords.
Enum traffic light;
{red , green, yellow}
Traffic light t1;
t1=traffic light. Red;
Enumeration are strongly typed consts, which allows u to assign
symbolic names to integral values.

PROGRAM:
Namespace enumeration{
Public enum color {red=1, green, yellow}
Class program{
Static void main (string[ ] args){
Console.WriteLine (“please select 1 for red, 2 for green, 3 for
yellow”);
String.str = console.ReadLine( );
Int colint= int 32.parse (str);
Color col= (color) colint;
Switch (col) {
Case color red;
Console.WriteLine (“selected color is red”)
Break;
default :
}
Console.ReadLine( );

2.​ Reference type: passed by refs to calling functions.


-​ Variables to refer to the objects store the ref of the actual data.
-​ Any change made in the new copy modify the copy to which object
is referenced.
-​ The reference type heap to store the references instead of actual
data.
-​ In C# heap is called manage heap, as it manages & maintains a
pointer to the add where the next object is to be allocated.
-​ The ref types are categorized into 2 types.
a.​ Pre-defined b. User-defined.
2.​ Pre-defined ref type: C# provides the following built-in ref types.
1.​ Dynamic types.
2.​ Object type.
3.​ String type.

1.​ Dynamic types: performs type checking of dynamic type variable at


runtime instead of compile time.
-​ U can add any type of value in dynamic type variable. This type is
similar to object type.(diff is type checking object type variable is
done at compile time). Declare dynamic variable using dynamic
keyword. Dynamic dyn=10;
2.​ Object type: enables you to assign values of any time to variable of
object type
-​ Object is an alias for pre-defined System.Object class.
-​ The object type is ultimate bar class for other type in CTS→value
ref, pre-defined & user-defined types.
-​ All these type are derived directly or indirectly from object type.
-​ The object type can be assigned a value of any other type, but
before assigning a value it requests the type conversion.
-​ When a value type is converted to object type, the process is
known as boxing.
-​ When an object type is converted to value type the process is
known as unboxing.
-​ Object x; X=15; \\boxing
3.​ String type: enable u to assign string values to variables of string
type.
-​ The string type is an alias for system .string class.
-​ After creating an object of string type, u cannot change its value.
-​ String snm= “C#5.0”;
a.​ User-defined ref type: are defined by using pre-defined type.
User-defined ref types can be divided into 4 parts.
1.​ Classes, 2. Interface, 3. Delegates, 4. Arrays
1.​ Classes: In C#, all classes are user-defined data type and
considered as objects. All object are derived from a single class
called System.Object. All appns in C# are based on a class.
PROGRAM:
Class greeting {
Static void main (string [ ] args) {
System.Console.WriteLine(“welcome”);
}}
2.​ Interfaces: defines a set of functionalities that can be related to
any class or struct. They are similar to interface in JAVA, but are
more flexible.
●​ It is equivalent to abstract base class in C++.
●​ Interface interface name
{
\\ abstract method declarations in interface body
}
3.​ Delegates: is almost equivalent to Function points in C++ or C#
contains 2 kinds of objects-those that create a change & those that
respond to the change.
●​ A delegate acts as a tunnel b\w the 2 kinds of objects-moving
information from one side to another.
●​ C# delegate are class method and can be either static or instance
class methods. Public delegate int IntDelegate(int a);
●​ A simple delegate type is not a method or a function.
●​ It is a defined of a function pts.
4.​ Arrays: store number of variables or elements of same type at
contiguous memory location in an ordered manner.
●​ C# support array of value types & ref types, but in C#, array
cannot be created on stack.
●​ U cannot create an array statically in a method.
●​ Array must be allocated in heap.
int [ ] x= new int [10];
●​ U can access the length of the array.
int len = x. Length;
●​ C# also supports multi-dimensional array which must be allocated
on heap.
int multi x[ , ]= new int [5,5];
●​ C# has no notion of simple static array.
●​ Both single & multi-dimensional arrays are dynamic.

PROGRAM:
Class program{
Static void main (string[ ] args) {
\\ declare, multi-dimensional array
int [ , ] x= new int [3,3];
For (int i=0; i<=2; i++)
{
For (int j=0; j<=2; j++)
{
Console.WriteLine (“Enter element”);
X [i,j]= int.parse (Console. Read line());
}}
For (int i=0; i<=2; i++){
Console.WriteLine ( );
For (int j=0; j<=2; j++)
{
Console.Write (x[i,j]+”\t); } }

3. Pointer types: `. Both ptr & ref represent memory add but the
diff is that refers are tracked by garbage collector & ptr are not.

Char*c;
Int*[ ]x;
❖​VARIABLES: a variable is an identifier that denotes a storage
location in memory.
●​ It stores numeric & string values that might change during
program execution.
Int i= 15;
●​ A variable can be declared as local or class variable.
●​ C# also provides static class variable.
●​ Variables can be of array types.
●​ U can declare the nullable type variables
●​ After the declaration, u can assign the normal range of values as
well as null value to a nullable type.

PROGRAM: (on nullable types)


Class prog {
Static void main(string[ ]args)
Int ? Var 1=null; // declaring null type variable
Int var 2=5;
Var1= var2; // valid
// int? Is Nullable where underlying type is int
If (var1. Has value==true)
{
Console.WriteLine(“var1=”+var1.value);
}
Else {
Console.WriteLine(“var1 null”)
}
Console.ReadLine( );
}}
Output: var1=5

❖​CONSTANTS: a constant is used to store a value. The value of a


const does not change during the execution of a prog.
Const double e=2.718;

❖​EXPRESSIONS & OPERATORS:


●​ An exp is a set of lang elements arranged together to perform a
specific task or computation.
●​ To use exp, C# 5.0 provides a complete set of language
elements→variables, constants, operators, properties & literals.

❖​OPERATORS: play a vital role in performing some computation or


other operations, → arithmetic & logical ops on the operands.
1.​ Arithmetic operators: +, -, *, /, %.
2.​ Relational operators: >, <, <=, >=, ==, !=.
3.​ Logical operators: &&, ||, ! (short-circuit AND OR)
4.​ Unary operators: ++, --
5.​ Multi assignment operators: +=, -=, *=, /=, %=.
6.​ Concatenation operators: +, +=.
7.​ Bitwise operators: &, λ, (XOR), <<(left shift), ~ (1’s
complement), >>(right shift)
8.​ Type information operators: is, as, type of, size of.
9.​ Ternary (conditional operators): ? :
10.​ Reference, indirection operators: &, *, →.
11.​ Access operators: . (dot)
12.​ Stmt separation: ;
13.​ Null coalescing: ??(depending on null value it return either 1
value)
●​ Unary operators: ++, -- , Int a=10, b; , b=a++;
●​ C lang: Int =18; Printf (“%d %d %d %d %d \n”, a,a++, a--,
++a, --aa)
●​ C#: Int a=18;
Console.WriteLine(a+ “ ” + a++ + “ ” + a-- + “ ” + ++a +
“ ” + --a);

(? : ) c=(a>b)?a:b;

❖​Operator precedence
o​ We can use many of the expressions to perform required
calculations
o​ C# associates precedence with each operator to define the
evaluation order of expression.
o​ Associativity is either left or right

1.​ *=, /=, %=+=, -=,<<=,>>=,&=,^=,|=,=,?: - right


2.​ ||,|,&&,^,&,==,!=,<,>,<=,>=,is,as,<<,>>,+(arithmetic),-(arithm
etic),*,/,%,unary+,- .... – left
▪​ Using the ?? (NULL COALESCING) operator
o​ Null coalescing (??): returns one of 2 values depending on the null
values.
●​ It returns the lf operand if its value is not null; otherwise, it return
the right operand
●​ The null coalescing operator(??) is mostly used with the nullable
value type & ref type.
●​ The ?? operator is used b\w 2 operands where the 1st operand
must be of null-able type.
●​ 2nd operand must be of the same type as the 1st operand or of the
type that can be implicitly convert to 1st type.
●​ If the 2nd operand cannot be implicitly converted to 1st operand, a
compile-time error is generated.

PROGRAM:
Class program {
Static void main(string[ ] args) {
Int? i=null; // nullable var
Int? j=30; // nullable var
Int k;
K=i ?? 25; //using ?? operator to check the null value
Console.WriteLine(“the val of k is”+k);
K=j ?? 25;
Console.WriteLine(now “the value of k=”+k);
}}

Output : the value of k is 25.


Now the value of k=30;
▪​ USING Is & as operators:
●​ Is operator checks whether an object is compatible with the given
type & returns a boolean result.
●​ The as operator converts the ref types explicitly into specific types.
●​ If the ref type is compatible with specified type, it performs
successful conversion, otherwise it returns null value.
●​ As operator does not throw an exception.

Program:
Object i=25;
Object str = “welcome”;
If (i is string)
Console.WriteLine(“i is a string type”);
{
Else
Console.WriteLine(“ i is an int type”);
String s1=i as string ; \\ casting i to string
String s2= str as string; \\ casting str to string
Console.WriteLine(“the val of s1 is”+s1);
Console.WriteLine(“the val of s2 is”+s2);

Output: i is an int type


The val of s1 is,
The val of s2 is welcome
❖​TYPE CONVERSION: converting one data type to another is
known as type casting.
●​ Type casting has 2 forms- 1.implicit, 2. Explicit.
1.​ Implicit conversion: conversion that are performed by the PL, in a
type-safe manner, (for ex, converting an int in floating-point no is
done implicitly)
Int i=123;
Single 3=i;
●​ Built-in conversion method in C#: ToBoolean, ToByte, ToChar,
ToDateTime, ToDecimal, ToDouble.
●​ NOTE: the implicit conversions are not applied to the char type as
well as b\w floating pt type & decimal types.
2.​ Explicit conversion\type casting: when one data type is converted
explicitly to another data type, with the help of some pre-defined
functions, it is called explicit conversion.
●​ In explicit conversion, there are chances of data loss as such type
of conversion is forceful.
Single 5=12345f;
Int i=(int)5;
▪​ Boxing & Unboxing:
1.​ Boxing: it is the term used to describe the transformation from
value type to ref type(object) at runtime.
It create a temporary ref type box for the object on heap.
2.​ Unboxing: it is the term used to describe the transformation from
ref type (object) to value type, it should be converted explicitly.
Eg : int n=185;
Object o=n; // boxing
Console.WriteLine(o);
Int m= (int)o; // unboxing
Console. Write line(m);

1.​ Copies value to heap


2.​ Creates box for that value at
heap
3.​ Creates reference
4.​ Returns reference to object

1.​ When a value is boxed to an object type, that object type variable
cannot be used in mathematical express
2.​ When the value of object type variable cannot be assigned to
variable on if hand size “Invalid cast exception” is thrown.
3.​ Extensive use of object data type make the lang “loosely typed” &
also because of frequent boxing & unboxing performance is
degraded.
4.​ Boxing & unboxing is used only in a situation where, at runtime,
we do not know the type of data, we are going to deal with.

▪​ CONVERT CLASS: It is a built-in class available in system name


space used to convert the data from one system to other type.
-​ By default all conversion express are type safe.
-​ convert class has the following method.
Convert.ToChar(val)
Convert.ToByte(val)
Convert.ToBoolean(val)
Convert.ToString(val)
Convert.ToInt16(val)
Convert.ToInt32(val)
Convert.ToInt64(val)
Eg: int→byte
Int a=255;
Byte b=Convert.ToByte(a);
▪​ PARSING: it only convert string type to any other type.
String→Int
String s= “125”
Int a= int. Parse(s);
string→float
string→double
string s=12.5;
float a= float.parse(s);
double b= double.parse(s);
string s= “ABC”;
int a= int.parse(); // runtime error format exception
3.​ To check whether a string can be parsed to int or not
Int→string
int n;
string s= “abc”
bool b= int.Try parse(s, out n);
Console.WriteLine(b+ “ ”+n);
output: false o
❖​DESICION AND LOOP STATEMENTS
❖​Control flow statements:
4.​ Are used to change the flow of execution of a prog.
5.​ In C#, control flow stmts are divided into 3 categories.
1.​ Selecting stmts: executes a block of code only when a certain cond
or set of conditions is fulfilled.
2.​ Iteration stmts or loops: executes a specific block of code as long
as a certain cond is fulfilled.
3.​ Jump stmts: transfers the prog control from one block of code to
another.
1)​ SELECTION STATEMENTS:
1.​ If stmt
2.​ Switch stmt
1.​ If stmt: a) Simple if , b) If-else c) If-else-if d) Nested-if
a.​ If (num1>num2) \\ simple-if
{
--
}
b.​ If (num1>num2) \\ if-else
{
--
}else
{
-----
}
c.​ if-else-if
PROGRAM:
If (num1>num2) && (num1>num3) {
Console.WriteLine(“num1 is greatest”);
}Else if (num2>num3)
{
Console. WriteLine(“num2 is greatest”);
}Else{
Console.WriteLine(“num3 is greatest”);
}
d.​ Nested-if:
PROGRAM:
If (num1>num2 && num1 >num3)
Console.WriteLine(num1 + “is the largest no”);
Else
If (num2>num3)
Console.Writeline (num2 + “is the largest no”);
Else
Console.Writeline(num3 + “is the largest no”);

▪​ LEAP YEAR PROGRAM:


Class prog {
Static void main(string[ ] args)
{
Int yr;
Console. Write(“Enter the year val (yyyy):”);
Yr= Int 32.Parse (Console.ReadLine ( ));
If ((yr %4 ==0 && yr % 100 !=0) -- yr % 400 ==0)
Console.WriteLine(“the year{0}is a leap yr”,yr);
Else
Console.WriteLine(“the year {0}not a leap yr”,yr);
}}
2.​ Switch stmt:
PROGRAM:

Switch(var) {
case n\ ‘c’\ “string”:
stmt s;
Break ;

--

default :
stmt s;

Break;

1.​ Default block is optional


2.​ Default block can be written anywhere in switch case stmt.
3.​ Must terminate the case b\k with break.
4.​ From a case block, control can be transferred to default block by
using the following statement.
Go to default;
-​ Switch is similar to if-else-if, technically if is assumed to be best
&at readability “switch” is best.
PROGRAM:
Namespace days in month {
Class program {
Static void main(string[ ] args)
{
String month;
Console.WriteLine(“enter the name of a month”)
Month= Console.ReadLine( ).ToUpper( );
Switch (month)
{
Case “JAN”:
Case “MAR”:
Case “MAY”:
Case “JULY”:
Case “AUG” :
Case “OCT”:
Case “DEC”:
Console.WriteLine(month+ “has 31 days”);
Break ;
Case “APR”:
Case “JUNE”:
Case “SEP”:
Case “NOV”:
Console. WriteLine(month+ “has 30 days”);
Break;
Case “FEB”:
Console.WriteLine(month+ “has 28 days”);
Break;
Default:
Console.WriteLine(“u have entered an invalid month name”);
Break;
}
Console.Write(“\n press ENTER to quit”);
Console. Read line ( );
}}}
2)​ ITERATION STMTS OR LOOPING CONSTRUCTS:
1.​ While-loop: evaluates a condition before executing a loop. The loop
continues executing as long as specified condition is true.
2.​ Do-while loop: executes the loop body atleast once before
evaluating a cond.
3.​ For loop: continues to execute the loop body until the condition
specified in the loop becomes false.
4.​ For each loop: continues to execute the loop body for each
element in an array or object collection.
1.​ While (cond) 2. Do
{ {
Stmt; stmt;
} } while(cond);

3.​ For (initialize; cond; loop exp)


{
stmts;
}
For(int i=1; i<=5; i++)
Console.WriteLine(i);
4.​ For each loop : iterates through all the items in a list. The list may
be an array or collection of objects.
For each (<data type> <var nm> in <array-nm>)
{
\\ stmts;
}
-​ String title = new string [ ] {“JAVA”, “C++”, “C#”, “VB”};
-​ For each (string i in title)
Console.WriteLine (“\t” +i);
3)​ JUMP STATMENTS: allow u to move the prog control from 1 point
to another.
❖​ In C#, there are 5 types of jump stmts.
1.​ Go to stmt: transfers the prog control directly to a labelled stmt.
The stmt or block of stmt which have been given
some name or label is known as labelled stmt.
PROGRAM:
If (num1>num2) {
If(num1>num3) {
Go to my label;
}}
label : \\ labelled stmt:
{
Console.WriteLine (“num1 is greater”)
}
2.​ Break stmt: terminates the loop in which it appears.
3.​ Continue stmt: transfers the prog control to the next iteration of
loop, in which continue keyword appears.
4.​ Return stmt: terminates the execution of the method in which it
appears & returns control to calling method.
5.​ Throw stmt: specifies the occurrence of an exception explicitly.
●​ PROGRAM:
For (num=1; num<=10;num++) {
Console.WriteLine (num);
If (num>=5)
Break;
}
Output: 1,2,3,4,5

PROGRAM:
For (num=1; num<=10; num++) {
If (num<=5)
Continue;
Console.WriteLine (num);
}
Output:6,7,8,9,10
Comma in a for stmt:
PROGRAM:
Int i,j;
For (i=0; j=10; i<j; i++, j--)
Console.WriteLine(“i & j” +i+ “ ” +j);
Output: i & j: 0 10
1​ 9
●​ GENERICS: allow u to delay the specification of the data type of
programming elements in a class or a method, until it is actually
used in the prog.
-​ Generics allow u to write a class or method that can work with any
data type.
-​ Write the specifications for the class or the method, with substitute
parameters for data type.
-​ Generics are a type of fixed data structure which can be reused by
passing different type of parameters
-​ Parameters are classes struct interfaces
-​ Generics are use to provide the reusability of code in s/w
components
-​ U can create generic collection, which can handle the collections of
datatypes in safe manner
-​ In generics instead of specifying the parameter we defined labels
which can later be replaced by the datatype. Label like “TP”
-​ When the compiler encounters a constructor for the class or a
function call for the method, it, generate code to handle the
specific data type. (like templates)
PROGRAM:
Using System;
Using System.Collections.Generic;
Namespace Generic Application {
Public class My Generic Array<T> {
Private T [ ] array;
Public My Generic Array(int size) {
Array= new T[size+1];
}
Public T get item (int index) {
Return array [in index];
}
Public void set item(int index, T val)
{
Array[index]=val;
}}
Class tester {
Static void main(string[ ] args) {
//declaring an int array
MyGenericArray<int> int arr=new MyGenericArray<int>(5);
//setting values
For (int c=0; c<5; c++) {
Int arr.SetItem (c, c*5);
}
\\retrieving the vals:
For (int c=0; c<5; c++)
{
Console. Write(int arr.GetItem(c)+ “ ”);
}
Console.WriteLine ( );
\\declaring a char. Arr
My Generic Array<char> char array=new My Generic Array
<char>(5);
//Setting vals
For (int c=0; c<5; c++)
{
Chararray. SetItem( c, (char) (c+97));
}
//retrieving the val
For (int c=0; c<5; c++)
{
Console. Write(chararray. GetItem(c)+ “ ”);
}
Console.WriteLine( );
Console.Readkey( );
}}}
Output: 0 5 10 15 20
a b c d e
●​ FEATURES OF GENERIC:
o​ It help u to maximize code reuse, type safety, & performance
o​ U can create generic classes. The .Net framework class library
contains several new generic collection classes in the
System.Collection.Generic namespace. U may use these generic
collection classes instead of collection classes in System. Collection
namespace.
o​ U can create your own generic interfaces, classes, method,
events& delegates.
o​ U can create generic classes constrained to enable access to
method on particular data type.
●​ Generic collection CLASSES in .net
-​ Number of classes to create a generic collection
-​ Collection of classes& strongly typed
-​ This method as different functionalities such as
1.​Sorting elements
2.​Reversing the order of elements
3.​Searching a particular elements
-​ Generic classes allows u to make generic collection of key/value
pair
-​ Key/value pair allow u to add, sort& search elements
-​ Generic collection classes:
1.​List<T>class - easy to use substitute of array such as sort, reverse
& find.
2.​Linkedlist<T>class- later u can retrieve values.
3.​sortedlist<Tkey,Tvalue>class- retrieve the values with key or index.
4.​dictionary<Tkey,Tvalue>class- retrieve the objects using keys.
5.​sorted dictionary<Tkey,Tvalue>class- adds & sorts items on basis
of key.
6.​stack<T>class- store objects &the object added at last & reterived
at first
7.​queue<T>class – object added first to the collection retrieved first
8.​hash set<T>class – does not contain duplicate elements.

❖​NAME SPACES:
-​ allows to group diff entities such as classes, objects & functions
under a common name.
-​ A name space is a wrapper that is wrapped around 1 or more
structural elements to make them unique & differentiated from
other elements.
-​ A name space is a logical collection of classes & other type with
unique names.
-​ The struct of name space is like a true, where all related classes
are like leafs.
-​ EX:
Name space xyz corp
{
Public class corp 1{ }
Enum corp enum{ }
}
-​ All BCL being with name space system
-​ Ex: 1. For window based button
System. Windows. Forms
2.​ for web based button
System. Web.UI. webcontrols. Button
●​ 10,000+built-in classes
●​ JDBC same as ADO. Net
●​ To work with OLEDB. NET provides- system. Data. Oledb
System. Data. Sql client- for SQL server
System. Data. Oledb- for other data based
●​ Nested namespace:
Namespace corporation {
Namespace dept {
Namespace proj {
Class internal class { }
}}}
❖​OOPS:
Oops uses the concept of classes of objects to reuse the existing
code. A class acts as a blue print or template to create instances or
objects.
❖​ENCAPSULATION:
●​ is the process of hiding the irrelevant information & showing only
the relevant information of a specific object to a user.
-​ In terms of oop, encapsulation is the process of wrapping up data
& memory’s of a class .
-​ It is an approach of hiding the internal state & behaviour of a class
or an object from unauthorized access.
-​ Encapsulation restricts users from sharing and manipulating data;
thereby, minimizing the chances of data corruption.
-​ To save our precious data from unauthorized access& corruption ,
declare it with PRIVATE keyword
-​ Accessor &mutators are method that are used get &set the values
of variable
-​ In c# encapsulation is implemented by using private access
specifier
▪​ Advantages of encapsulation:
1.​ Provides a way to protect our data from unauthorized access.
2.​ Increases the maintainability of the code by showing only the
relevant information to a user.
3.​ Prevents data corruption by enabling private memory variable of a
class to be accessed through specific method.
4.​ Binds memory variables & functions of a class into a single unit.
●​ PROGRAM:
Namespace employee{
Public class employeedetail {
Private string Name;
// accessor
Public void Set(string name) {
Name= name;
}
Public string get() {
Return Name;
}
//mutators
}
Public class main class {
Static void main(string[] args) {
Employeedetail detail = new employeedetail();
Detail.set(“raju”);
Console.WriteLine(“the employee name is :” +detail.get());
Console.Write(“\npress enter to quit.....”);
Console.ReadLine()
}}}

❖​INHERITANCE :
The most important reason to use oop is to promote reusability of
code & reduce redundancy.
-​ Inheritance is the property through which a class derives
properties from another class.
-​ A class that inherits the properties of another class is called a child
or derived class; whereas, the class from which the child class
inherits properties is known as parent or base class.
-​ Parent class is at a higher level in class hierarchy .
-​ A class hierarchy defines the logical structuring of the classes such
that a general class is on the top & more specialized classes are at
lower levels.
-​ Inheritance is of 4 types,
1.​ Single inheritance : there is only one base class & one derived
class.
2.​ Hierarchical inheritance: multiple derived classes are inherited from
same base class.
3.​ Multilevel inheritance: refers to inheritance in which a child class is
derived from a class, which in turn is derived from another class.
4.​ Multiple inheritance: refers to inheritance in which a child class is
derived from multiple base classes.
●​ NOTE: C# supports single, hierarchical & multi level inheritance
because there is only a single base class. It does not support
multiple inheritance directly. Use interfaces to impl. Multiple
inheritance.

●​ PROGRAM:
Namespace My Inheritance {
Public class base class {
Public int i;
Public void base method 1( ) {
Console.WriteLine(“I’ am a base class method”);
}}
Public class derived class: base class
{
Public void derived method ( )
{
Console. Write line (“I’ am a derived class method”);
}}
Public class program {
Static void main (string[ ] args) {
Console.WriteLine (“Inheritance demo”);
base class BC = new base class ( );
BC.i =1;
BC. BaseMethod1( );
Derived class DC=new derived class( );
DC.i=2;
DC. base method 1( );
DC. derived method ( );
Console.Write(“\n press enter to quit:”);
Console.ReadLine( );
}}}
▪​ CONSTRUCTOR: is a special method of a class, which is used to
initialize the memory of the same class. A constructor is called by
default whenever an object of a class is created.
▪​ Sealed classes & Sealed methods:
-​ Sealed classes are classes that cannot be inherited.
-​ U can define use the sealed keyword to define a class as sealed
class
-​ A sealed class can contain a method
-​ A derived class cannot override the sealed method
-​ U can use sealed method to override an inherited virtual method
with the same signature.
-​ U always use sealed keyword with the combination of override
keyword
-​ (like final in java). Use sealed keyword.

PROGRAM:
Sealed class <class nm> {
// data memory’s & memory function
}
❖​POLYMORPHISM:
-​ Imp feature of oop- exhibit diff forms of any particular proc- one
proc can be used in many ways.
-​ The advantages of polymorphism.
1. Allows u to invoke method of a derived class through base class
ref during runtime.
2. Provides diff impls of methods in a class that are called through
the same name.
- There are 2 types of polymorphism.
a.​ Static polymorphism/compile time polymorphism/over loading.
b.​ Dynamic polymorphism/runtime polymorphism/override.
a.​ Compile time polymorphism/over loading:
-​ It bind the appropriate method to an object at compile time
itself(early binding) – can be implied through overloaded method &
operators.
-​ Overloaded method are the methods that have same name but diff
signatures, such as no, type & seq of parameters.
-​ There are 3 types of compile time polymorphism.
1.​ Method overloading.
2.​ Operator overloading.
3.​ Indexer overloading.
1.​ Method overloading:
-​ Method behaves according to the no & type of parameters passed
to it.- u can define many methods with the same name but diff
signatures.
-​ A method sign is the combination of the method’s name along
with the no, type & order of parameters.
-​ Compiler automatically determines which method should be used
according to sign specified in method call.

PROGRAM:
Public class shape {
Public void Area(int side) {
Int Sarea =side*side;
Console.WriteLine(“area of square is” +Sarea);
}
Public void Area (int len, int b) {
Int rarea= len*b;
Console.Writeline(“area of rectangle is”+rarea);
}
Public void area(double radius) {
Int carea=3.14*radius*radius
Console.Writeline(“area of circle is” +carea);
}
Public void area(double base, double height) {
Double tarea= base*height\2;
Console. Writeline(“area of triangle is” +tarea);
}
Class mainclass {
Static void main (string[ ] args) {
Shape s= new shape( );
s. Area (15);
s. Area (10,20);
s. Area (10.5);
s. Area (15.5,20.4);
Console.Writeline(“\n press Enter to quit”);
Console.Readline( );
}}
2.​ OPERATOR OVERLOADING:
-​ All operators have specified meaning & functionality – u can
change the functionality of an operator by overloading them.
-​ It is not possible to overload all operators &&, ||,( ), assignment, .,
?:,→,new, is, size of, type of can not be overloaded.
-​ To overload an operator, create a method that must be preceded
by operator keyword.
3.​ Indexer overloading:
-​ In C#, indexer is use to treat an object as an array.
-​ It is use to provide index to an object to obtain values from the
object.
-​ Implementing an indexer requires u to use brackets with([ ]) an
object to get & set a value of the object.

PROGRAM:
Public string this[int pos] {
Get { return My Data[pos]
}
Set{ My Data[pos]=val;}
b.​ RUNTIME POLYMORPHISM/OVERRIDING:
-​ Allows a derived class to provide a specific impl of a method that is
already defined in a base class.
-​ The impl. of method in derived class overrides or replaces the impl.
of method in its base class.
-​ Complier binds a method to an object during the execution of a
program- the method defined in derived class is executed instead
of one in base class.
-​ To invoke method of a derived class, that is already defined in base
class, u need to perform the following steps.
1.​ Decl. The base class method as virtual.
2.​ Impl. Derived class method using override, keyword
●​ PROGRAM:
Class baseclass {
Public virtual void show data( ) {
\\ method body
}}
Class derived class : base class {
Public override void showdata( ) {
\\ method body
}}

❖​ABSTRACTION:
-​ Process of hiding the details of a particular concept or object from
a user & exposing only the essential features.
-​ Refer to act of repairing essential features without including the
background details or explanation.
-​ Denote a model, view or a rep. For an actual item.
-​ The main characteristics of abstraction are.
1.​ Managing the complexity of the code.
2.​ Decomposing complex systems information into smaller
components .
▪​ ABSTRACT CLASSES: In C#, u can have single base class &
multiple derived classes. Abstract class cannot be instantiated.
❖​ PROGRAM:
Abstract class baseclass {
\\ memories
}
Class derived class: baseclass {
\\ memories
}
class mainclass
}
Baseclass bc; \\ can’t be instantiated
Derived dc; \\ can be instantiated
}
o​ Characteristics of abstract class:
1.​ Restricts instantiation.
2.​ Allows u to define abstract & non-abstract method.
3.​ Requires atleast one abstract method in it.
4.​ Restricts the use of sealed keyword in it.
5.​ Possesses public access specifier.
▪​ ABSTRACT METHOD: Similar to virtual method, which does not
provide any impl.(no body).
Public abstract void area (int len,int b);
o​ Characteristics of abstract method:
1.​ Restricts its impl. In an abstract class.
2.​ Allows impl. In a non-abstract derived class.
3.​ Requires decl. In an abstract class only.
4.​ Restricts decl. With static & virtual keywords.
5.​ Allows u to override a virtual method.
❖​INTERFACES:
-​ Is a collection of data memories & memory functions, but it does
not impl. them.
-​ They only specify the parameter that they will take & the types of
values they return.
-​ An interface is always impl. in a class (need to impl. all memory of
interface).
-​ In C# interfaces are more flexible in their impl.
-​ It is equivalent to abstract base class.
PROGRAM:
Interface <interface name> {
\\ abstract method decl.
}
-​ When an interface is imled by a base class, then the derived class
automatically inherits methods of interface.
-​ Implementing an interface is similar to inheriting a class
PROGRAM:
Public interface channel {
Void next( );
Void previous( );
}
Public interface book {
Void next( );
Void chapter( );
}
Class program : channel, book
{
Void channel. Next ( ) {
Console.WriteLine (“channel next”);
}
Void book. Next ( )
{
Console. Writeline (“book next”);
}
Public void previous( ) {
Console.WriteLine(“previous”);
}
Public void chapter( )
{
Console.WriteLine(“chapter”);
}
Static void main (string[ ] args)
{
Program app=new program( );
((book) app).Next ( );
App.Previous ( );
App.Chapter( );
Console.WriteLine(“press enter to quit”);
Console.ReadLine( );
}}}

You might also like