Introduction to C#
Introduction to C#
❖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( );
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.
(? : ) 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
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);
}}
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);
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.
Switch(var) {
case n\ ‘c’\ “string”:
stmt s;
Break ;
--
default :
stmt s;
Break;
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( );
}}}