0% found this document useful (0 votes)
71 views200 pages

Harsha Vardhan

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 200

C#.NET 8.

0
Harsha Vardhan
.NET Expert
C#.NET 8.0

.NET Fundamentals........................................................................................................................ 26
Introduction to .NET ............................................................................................................. 26
What is .NET? ....................................................................................................................... 26
Parts of .NET ......................................................................................................................... 26
History of .NET...................................................................................................................... 27
History of .NET...................................................................................................................... 27
Versions of .NET ................................................................................................................... 29
CIL and CLR ........................................................................................................................... 30
Execution Model of .NET Programs ..................................................................................... 30
CIL (Common Intermediate Language) or MSIL ................................................................... 31
CLR (Common Language Runtime)....................................................................................... 31
Sub Components of CLR ....................................................................................................... 32
.NET Framework Architecture .............................................................................................. 34
What is .NET Framework ...................................................................................................... 34
System Requirements of .NET Framework: ......................................................................... 34
.NET Framework Architecture .............................................................................................. 35
CLS and CTS .......................................................................................................................... 36
CLS (Common Language Specification) ................................................................................ 36
CTS (Common Type System) ................................................................................................ 36
FCL and BCL .......................................................................................................................... 37
FCL (Framework Class Library) ............................................................................................. 37
Introduction to Visual Studio ............................................................................................... 38
What is Visual Studio ............................................................................................................ 38
Versions of Visual Studio ...................................................................................................... 38
System Requirements of Visual Studio 2019: ...................................................................... 39
Project .................................................................................................................................. 40
Solution ................................................................................................................................ 40
File Types of .NET ................................................................................................................. 40
Folder Structure of .NET Project in Visual Studio ................................................................ 41

D. Harsha Vardhan (.NET Expert) P a g e 2 | 1583


C#.NET 8.0

Visual Studio - Installation .................................................................................................... 42


Steps to install “Visual Studio 2019”: ................................................................................... 42

C#.NET – Language Fundamentals .......................................................................................... 55


Introduction to C#.NET ......................................................................................................... 55
What is C#.NET: .................................................................................................................... 55
Versions of C#.NET ............................................................................................................... 56
Tokens of C#.NET.................................................................................................................. 56
Naming Conventions for Identifiers ..................................................................................... 57
Identifier Naming Rules ........................................................................................................ 57
Console Applications - Introduction ..................................................................................... 58
What is Console Application? .............................................................................................. 58
Rules of Console Application ................................................................................................ 58
Console Application - Example ............................................................................................. 59
The “System.Console” class ................................................................................................. 60
1. System.Console.Write().................................................................................................... 60
2. System.Console.WriteLine() ............................................................................................. 61
3. System.Console.ReadKey() ............................................................................................... 61
4. System.Console.ReadLine() .............................................................................................. 61
5. System.Console.Clear() .................................................................................................... 61
System.Console.WriteLine – Example.................................................................................. 62
System.Console.ReadKey – Example ................................................................................... 63
System.Console.Clear - Example .......................................................................................... 65
Variables ............................................................................................................................... 68
Variables - Example .............................................................................................................. 69
Data Types ............................................................................................................................ 71
Types of Data types .............................................................................................................. 71
Numerical Data Types .......................................................................................................... 71
Default Numerical data types .............................................................................................. 72
Non-Numerical Data Types .................................................................................................. 73
Numerical Data Types - Example ......................................................................................... 73
MinValue and MaxValue ...................................................................................................... 76

D. Harsha Vardhan (.NET Expert) P a g e 3 | 1583


C#.NET 8.0

MinValue and MaxValue - Example ..................................................................................... 76


char - Example ...................................................................................................................... 78
String .................................................................................................................................... 79
String - Example.................................................................................................................... 80
Bool - Example ...................................................................................................................... 81
Operators ............................................................................................................................. 83
Arithmetical Operators ........................................................................................................ 83
Arithmetical Operators - Example........................................................................................ 84
Assignment Operators.......................................................................................................... 86
Assignment Operators - Example ......................................................................................... 86
Increment / Decrement Operators ...................................................................................... 88
Increment / Decrement Operators - Example ..................................................................... 88
Relational Operators ............................................................................................................ 90
Relational Operators - Example ........................................................................................... 90
Logical Operators ................................................................................................................. 92
Logical Operators - Example................................................................................................. 93
Concatenation Operator ...................................................................................................... 94
Concatenation Operator - Example ..................................................................................... 95
Conditional Operator ........................................................................................................... 96
Conditional Operator - Example........................................................................................... 96
Control Statements .............................................................................................................. 98
Types of control statements: ............................................................................................... 98
If............................................................................................................................................ 99
If - Example ......................................................................................................................... 101
If – Else - Example............................................................................................................... 102
Else – If - Example............................................................................................................... 104
Nested If - Example ............................................................................................................ 105
Switch – Case ...................................................................................................................... 107
Switch – Case - Example ..................................................................................................... 107
While .................................................................................................................................. 109
While - Example.................................................................................................................. 109

D. Harsha Vardhan (.NET Expert) P a g e 4 | 1583


C#.NET 8.0

Do – While .......................................................................................................................... 111


Do – While - Example ......................................................................................................... 111
for ....................................................................................................................................... 113
for - Example ...................................................................................................................... 113
Break................................................................................................................................... 115
Break - Example .................................................................................................................. 115
Continue ............................................................................................................................. 116
Continue - Example ............................................................................................................ 117
Goto .................................................................................................................................... 118
Goto - Example ................................................................................................................... 118
Nested For Loops................................................................................................................ 120
Nested For Loops - Example ............................................................................................... 120

C#.NET – Object Oriented Programming (OOP)...................................................................123


Introduction to Object Oriented Programming ................................................................. 123
Types of Programming Languages ..................................................................................... 123
Introduction of Object Oriented Programming (OOP) ....................................................... 124
Object ................................................................................................................................. 124
Fields................................................................................................................................... 125
Methods ............................................................................................................................. 125
Class .................................................................................................................................... 126
Reference variables ............................................................................................................ 128
Syntax of creating class ...................................................................................................... 128
Syntax of creating a Field in a class: ................................................................................... 128
Syntax of creating a method in a class: .............................................................................. 128
Syntax of creating reference variable ................................................................................ 129
Syntax of creating object (in heap): ................................................................................... 129
Memory allocation of Objects ............................................................................................ 129
Principles of Object Oriented Programming ...................................................................... 130
Principles of OOP ................................................................................................................ 130
Encapsulation: .................................................................................................................... 130
Abstraction: ........................................................................................................................ 130

D. Harsha Vardhan (.NET Expert) P a g e 5 | 1583


C#.NET 8.0

Inheritance: ........................................................................................................................ 130


Polymorphism: ................................................................................................................... 131
Types of polymorphism: ..................................................................................................... 131
Access Modifiers ................................................................................................................ 132
Access Modifiers ................................................................................................................ 132
Access Modifiers - Example................................................................................................ 135
Access Modifiers for classes ............................................................................................... 138
Access Modifiers for Classes .............................................................................................. 138
Object Oriented Programming – Example ......................................................................... 138
Object Oriented Programming – Student Example ........................................................... 140
Object Oriented Programming – Employee Example ........................................................ 142
Program.cs.......................................................................................................................... 143
Static Fields......................................................................................................................... 145
Static Fields - Example ........................................................................................................ 146
Constant Fields ................................................................................................................... 149
Constant Fields - Example .................................................................................................. 149
ReadOnly Fields .................................................................................................................. 151
ReadOnly Fields - Example ................................................................................................. 151
Methods ............................................................................................................................. 153
Methods – Simple Example ................................................................................................ 154
Methods – Arguments and Return Example ...................................................................... 155
Scope of Variables .............................................................................................................. 157
Methods – Example - Age .................................................................................................. 158
Methods – Example 2 - Numbers ....................................................................................... 160
Methods – Example 3 - Login ............................................................................................. 163
Methods – Example 4 - Student ......................................................................................... 165
"this" keyword .................................................................................................................... 170
"this" keyword - Example ................................................................................................... 170
Static Methods ................................................................................................................... 172
Static Methods - Example .................................................................................................. 173
Reference Variables as Arguments .................................................................................... 175

D. Harsha Vardhan (.NET Expert) P a g e 6 | 1583


C#.NET 8.0

Reference Variables as Arguments - Example ................................................................... 175


Reference Variables as Fields ............................................................................................. 177
Reference Variables as Fields - Example ............................................................................ 177
Default Arguments ............................................................................................................. 179
Default Arguments - Example ............................................................................................ 179
Named Parameters ............................................................................................................ 181
Named Parameters - Example............................................................................................ 181
Methods Overloading......................................................................................................... 183
Methods Overloading - Example ........................................................................................ 183
Types of Parameters........................................................................................................... 185
Call by value - Example....................................................................................................... 186
Call by reference - Example................................................................................................ 187
Call by output - Example .................................................................................................... 189
Type Conversion ................................................................................................................. 191
Implicit Casting - Example .................................................................................................. 191
Explicit Casting (or) Type Casting ....................................................................................... 193
Explicit Casting (or) Type Casting - Example ...................................................................... 193
Parsing ................................................................................................................................ 195
Parsing - Example ............................................................................................................... 195
TryParse .............................................................................................................................. 197
TryParse - Example ............................................................................................................. 197
TryParse – Example 2 ......................................................................................................... 199
Output ................................................................................................................................ 200
Conversion Methods .......................................................................................................... 201
Conversion Methods - Example ......................................................................................... 202
Constructors ....................................................................................................................... 204
Types of Constructor .......................................................................................................... 204
Default Constructor ............................................................................................................ 205
Parameterless Constructor - Example................................................................................ 205
Parameterized Constructor - Example ............................................................................... 207
Constructors - Student - Example ...................................................................................... 209

D. Harsha Vardhan (.NET Expert) P a g e 7 | 1583


C#.NET 8.0

Object Initializer ................................................................................................................. 212


Object Initializer - Example ................................................................................................ 212
"Set" and "Get" Methods ................................................................................................... 216
Set Method ......................................................................................................................... 216
Get Method ........................................................................................................................ 216
"Set" and "Get" Methods - Example .................................................................................. 217
Properties ........................................................................................................................... 219
Properties - Example .......................................................................................................... 221
Readonly and WriteOnly Properties .................................................................................. 223
Readonly Properties - Example .......................................................................................... 224
Automatic Properties ......................................................................................................... 226
Automatic Properties - Example ........................................................................................ 226
Inheritance ......................................................................................................................... 228
Inheritance - Example ........................................................................................................ 228
Inheritance – Example 2 ..................................................................................................... 231
“base” keyword .................................................................................................................. 234
“base” keyword - Example ................................................................................................. 234
Parent class’s constructor .................................................................................................. 237
Parent class’s constructor - Example ................................................................................. 237
Method Hiding ................................................................................................................... 241
Method Hiding - Example................................................................................................... 242
Method Hiding – Example 2 ............................................................................................... 244
Method Overriding ............................................................................................................. 247
Normal Methods (vs) Virtual Methods .............................................................................. 247
Method Hiding (vs) Method Overrinding ........................................................................... 248
Method Overriding - Example ............................................................................................ 249
Method Overriding – Example 2 ........................................................................................ 251
Abstract Classes.................................................................................................................. 254
Abstract Classes - Example ................................................................................................. 255
Abstract Classes – Example 2 ............................................................................................. 257
Abstract Methods............................................................................................................... 260

D. Harsha Vardhan (.NET Expert) P a g e 8 | 1583


C#.NET 8.0

Abstract Methods - Example .............................................................................................. 262


Abstract Methods – Example 2 .......................................................................................... 264
Interfaces............................................................................................................................ 268
Abstract Class (vs) Interface ............................................................................................... 268
Interfaces - Example ........................................................................................................... 271
Interfaces – Example 2 ....................................................................................................... 273
Dynamic Polymorphism ..................................................................................................... 276
Dynamic Polymorphism - Example..................................................................................... 277
Dynamic Polymorphism – Example 2 ................................................................................. 279
Multiple Inheritance using Interfaces ................................................................................ 282
Multiple Inheritance using Interfaces - Example ............................................................... 282
Interface Inheritance .......................................................................................................... 286
Interface Inheritance - Example ......................................................................................... 286
Sealed Classes..................................................................................................................... 290
Sealed Classes - Example .................................................................................................... 290
Namespaces ....................................................................................................................... 293
Namespaces - Example ...................................................................................................... 293
Child Namespaces .............................................................................................................. 296
Child Namespaces - Example ............................................................................................. 296
Child Namespaces – Example 2 .......................................................................................... 298
“using” statement .............................................................................................................. 301
“using” statement - Example ............................................................................................. 301
“using - alias” statement .................................................................................................... 303
“using - alias” statement - Example ................................................................................... 303
Creating Separate Files for Classes .................................................................................... 306
Creating Separate Files for Classes - Example.................................................................... 306
Partial Classes ..................................................................................................................... 309
Partial Classes - Example .................................................................................................... 309
Enumerations ..................................................................................................................... 313
Enumerations - Example .................................................................................................... 313
Structures ........................................................................................................................... 316

D. Harsha Vardhan (.NET Expert) P a g e 9 | 1583


C#.NET 8.0

Structures - Example .......................................................................................................... 318


Structures with Constructors - Example ............................................................................ 320
Standard Data Types .......................................................................................................... 323
The "System.Object" class .................................................................................................. 324
“System.Object” Class - Example ....................................................................................... 324
Methods of "System.Object" class ..................................................................................... 326
Methods of “System.Object” class - Example .................................................................... 327
Boxing ................................................................................................................................. 330
Boxing - Example ................................................................................................................ 330
Unboxing ............................................................................................................................ 332
Unboxing - Example ........................................................................................................... 332
Static Constructors ............................................................................................................. 334
Static Constructors - Example ............................................................................................ 335
Static Classes ...................................................................................................................... 338
Static Classes - Example ..................................................................................................... 338
Generic Classes................................................................................................................... 341
Generic Classes - Example .................................................................................................. 341
Multiple Generics - Example .............................................................................................. 343
Arrays ................................................................................................................................. 346
Arrays - Example................................................................................................................. 346
Arrays with For Loop .......................................................................................................... 348
Arrays with For Loop - Example ......................................................................................... 348
Arrays with Foreach Loop in C#.NET .................................................................................. 350
Arrays with Foreach Loop – Example ................................................................................. 350
“System.Array” class .......................................................................................................... 353
“System.Array.IndexOf” method ....................................................................................... 354
“System.Array.IndexOf” method - Example....................................................................... 354
“System.Array.IndexOf” method – with NotFound - Example .......................................... 356
“System.Array.BinarySearch” method ............................................................................... 358
“System.Array.BinarySearch” method - Example .............................................................. 358
“System.Array.Clear” method ............................................................................................ 360

D. Harsha Vardhan (.NET Expert) P a g e 10 | 1583


C#.NET 8.0

“System.Array.Clear” method - Example ........................................................................... 360


“System.Array.Resize” method .......................................................................................... 363
“System.Array.Resize” method - Example ......................................................................... 363
“System.Array.Sort” method ............................................................................................. 366
“System.Array.Sort” method - Example............................................................................. 366
“System.Array.Reverse” method ....................................................................................... 368
“System.Array.Reverse” method - Example ...................................................................... 368
“System.Array.CopyTo” method ........................................................................................ 370
“System.Array.CopyTo” method - Example ....................................................................... 370
Multi-Dimensional Array .................................................................................................... 373
Multi-Dimensional Array - Example ................................................................................... 373
Collections .......................................................................................................................... 376
List of collections classes in .NET: ...................................................................................... 376
Arrays (vs) Collections ........................................................................................................ 376
The "List" class.................................................................................................................... 377
The "List" class - Example ................................................................................................... 377
The "List" class – with “for” loop ....................................................................................... 380
The "List" class – with “for” loop - Example....................................................................... 380
The "List" class – with “foreach” loop ................................................................................ 382
The "List" class – with “foreach” loop - Example ............................................................... 382
"System.Collections.Generic. List.Add" method ................................................................ 384
"System.Collections.Generic. List.Add" method - Example ............................................... 384
"System.Collections.Generic. List.Insert" method ............................................................. 386
"System.Collections.Generic.List.Insert" method - Example ............................................. 386
"System.Collections.Generic. List.AddRange" method ...................................................... 388
"System.Collections.Generic. List.AddRange" method - Example ..................................... 388
"System.Collections.Generic. List.InsertRange" method ................................................... 391
"System.Collections.Generic. List.InsertRange" method - Example .................................. 391
"System.Collections.Generic. List.Remove" method in C#.NET ......................................... 394
"System.Collections.Generic. List.Remove" method - Example ........................................ 394
"System.Collections.Generic. List.RemoveAt" method ..................................................... 396

D. Harsha Vardhan (.NET Expert) P a g e 11 | 1583


C#.NET 8.0

"System.Collections.Generic. List.RemoveAt" method - Example..................................... 396


"System.Collections.Generic. List.Clear" method .............................................................. 399
"System.Collections.Generic. List.Clear" method - Example ............................................. 399
"System.Collections.Generic. List.IndexOf" method ......................................................... 401
"System.Collections.Generic. List.IndexOf" method - Example......................................... 401
"System.Collections.Generic. List.IndexOf" method – Not Found- Example..................... 403
"System.Collections.Generic. List.BinarySearch" method ................................................. 405
"System.Collections.Generic. List.BinarySearch" method - Example ................................ 406
"System.Collections.Generic. List.Contains" method ........................................................ 407
"System.Collections.Generic. List.Contains" method - Example ....................................... 407
"System.Collections.Generic. List.Reverse" method ......................................................... 409
"System.Collections.Generic. List.Reverse" method - Example......................................... 409
"System.Collections.Generic. List.Sort" method ................................................................ 411
"System.Collections.Generic. List.Sort" method - Example ............................................... 411
System.Collections.Generic. List - Sort Descending - Example .......................................... 413
Collection Filter .................................................................................................................. 415
Collection Filter - Example ................................................................................................. 415
LINQ .................................................................................................................................... 417
LINQ - Example ................................................................................................................... 417
Collection of Objects .......................................................................................................... 420
Collection of Objects - Example ......................................................................................... 420
Collection of Objects – Filter - Example ............................................................................. 422
Collection of Objects – LINQ - Example.............................................................................. 424
The "Dictionary" class ........................................................................................................ 427
The "Dictionary" class - Example........................................................................................ 427
The "SortedList" class ......................................................................................................... 429
The "SortedList" class - Example ........................................................................................ 429
The "Hashtable" class in .NET ............................................................................................ 431
The "Hashtable" class - Example ........................................................................................ 431
The "ArrayList" class in .NET .............................................................................................. 433
The "ArrayList" class - Example .......................................................................................... 433

D. Harsha Vardhan (.NET Expert) P a g e 12 | 1583


C#.NET 8.0

The "typeof" operator in .NET............................................................................................ 435


The "typeof" operator - Example ....................................................................................... 435
The "System.String" class (or) String Handling .................................................................. 439
“System.String.Length” - Example ..................................................................................... 442
“System.String.ToUpper” - Example .................................................................................. 444
“System.String.ToLower” - Example .................................................................................. 445
“System.String.GetChar” - Example ................................................................................... 447
“System.String.Substring” – Example 1 ............................................................................. 449
“System.String.Substring” – Example 2 ............................................................................. 450
“System.String.Remove” – Example .................................................................................. 451
“System.String.Remove” – Example 2 ............................................................................... 453
“System.String.Insert” – Example ...................................................................................... 455
“System.String.Equals” – Example ..................................................................................... 456
“System.StringComparison. OrdinalIgnoreCase” – Example ............................................. 458
“System.String.StartsWith” – Example .............................................................................. 459
“System.String.EndsWith” – Example ................................................................................ 461
“System.String.Contains” – Example ................................................................................. 462
“System.String.IndexOf” – Example 1 ................................................................................ 464
“System.String.IndexOf” – Example 2 ................................................................................ 465
“System.String.IndexOf” – Example 3 ................................................................................ 467
“System.String.LastIndexOf” – Example ............................................................................ 468
“System.String.Replace” – Example ................................................................................... 470
“System.String.ToCharArray” – Example ........................................................................... 471
Converting CharArray to String - Example ......................................................................... 474
“System.String.Split” – Example......................................................................................... 475
“System.String.Trim” – Example ........................................................................................ 477
“System.String.Format” – Example .................................................................................... 479
“System.String.Reverse” – Example ................................................................................... 480
String – WordsCount - Example ......................................................................................... 482
String – Character Occurrence Count - Example................................................................ 484
String – Alphabetic Count - Example.................................................................................. 486

D. Harsha Vardhan (.NET Expert) P a g e 13 | 1583


C#.NET 8.0

String – Word Occurrence Count - Example ...................................................................... 488


String – Title Case - Example .............................................................................................. 490
String – Currency into words - Example ............................................................................. 492
String – Multiple Concatenations - Example ...................................................................... 496
The "System.Text.StringBuilder" class ............................................................................... 498
The "System.Text.StringBuilder" class - Example .............................................................. 499
The "System.DateTime" structure (or) Date & Time Handling .......................................... 501
The "System.DateTime" – First Example ........................................................................... 503
The "System.DateTime.Now" –Example ............................................................................ 505
The "System.DateTime" – Inner Values – Example........................................................... 506
The "System.DateTime.DayOfWeek" – Example ............................................................... 508
The "System.DateTime.DayOfYear" – Example ................................................................. 510
The "System.DateTime. ToShortDateString" – Example.................................................... 511
The "System.DateTime. ToLongDateString" – Example..................................................... 513
The "System.DateTime. ToShortTimeString" – Example ................................................... 514
The "System.DateTime. ToLongTimeString" – Example .................................................... 516
The "System.DateTime" – Custom Formats – Example ..................................................... 517
The "System.DateTime.Subtract" – Example ..................................................................... 519
The "System.DateTime.AddDays" – Example .................................................................... 521
The "System.Math" class.................................................................................................... 523
The "System.Math.Abs" –Example .................................................................................... 524
The "System.Math.Floor" –Example .................................................................................. 526
The "System.Math.Ceiling" – Example ............................................................................... 527
The "System.Math.Round" – Example 1 ............................................................................ 528
The "System.Math.Round" – Example 2 ............................................................................ 530
The "System.Math.Max" –Example ................................................................................... 531
The "System.Math.Min" – Example ................................................................................... 533
The "System.Math.Pow" –Example ................................................................................... 534
The "System.Math.Sqrt" –Example .................................................................................... 536
“System.Diagnostics.Process” class ................................................................................... 538
“System.Diagnostics.Process” class - Example .................................................................. 538

D. Harsha Vardhan (.NET Expert) P a g e 14 | 1583


C#.NET 8.0

Command Line Arguments ................................................................................................. 540


Command Line Arguments - Example ................................................................................ 540
Nullable Data Types............................................................................................................ 543
Nullable Data Types - Example ........................................................................................... 543
Exception Handling............................................................................................................. 545
Exception Handling - Example ............................................................................................ 546
Destructor .......................................................................................................................... 549
Destructor - Example.......................................................................................................... 549
The "System.IDisposable" interface ................................................................................... 552
The "System.IDisposable" interface - Example .................................................................. 553
Garbage Collection ............................................................................................................. 555
Garbage Collection - Example ............................................................................................ 555
Delegates ............................................................................................................................ 557
Single Cast Delegates - Example......................................................................................... 558
Multi Cast Delegates - Example ......................................................................................... 560
Events ................................................................................................................................. 562
Events - Example ................................................................................................................ 563
Anonymous Methods ......................................................................................................... 566
Anonymous Methods - Example ........................................................................................ 566
Lambda Expressions ........................................................................................................... 569
Lambda Expressions - Example .......................................................................................... 569
Inline Lambda Expressions ................................................................................................. 572
Inline Lambda Expressions - Example ................................................................................ 572
Inner Classes ....................................................................................................................... 575
Inner Classes - Example ...................................................................................................... 575
Indexer................................................................................................................................ 578
Indexer - Example ............................................................................................................... 579
Assemblies .......................................................................................................................... 581
Class Libraries & Private Assemblies - Example ................................................................. 584
Shared Assemblies - Example............................................................................................. 588
Documentation Comments ................................................................................................ 593

D. Harsha Vardhan (.NET Expert) P a g e 15 | 1583


C#.NET 8.0

Documentation Comments - Example ............................................................................... 593


Extension Methods ............................................................................................................ 596
Extension Methods - Example ............................................................................................ 597

C# – Console - System.IO Namespace ..................................................................................601


Introduction to "System.IO" namespace ........................................................................... 601
The “System.IO.FileInfo” class ........................................................................................... 602
The “System.IO.FileInfo” class - Example........................................................................... 605
The “System.IO.DirectoryInfo” class .................................................................................. 607
The “System.IO.DirectoryInfo” class - Example ................................................................. 610
The “System.IO.Directory” class ........................................................................................ 613
The “System.IO.Directory” class - Example........................................................................ 614
The “System.IO.File” class .................................................................................................. 617
The “System.IO.File” class - Example ................................................................................. 618
The “System.IO.FileStream” class ...................................................................................... 621
The “System.IO.StreamWriter” class ................................................................................. 623
The “System.IO.StreamWriter” class - Example ................................................................ 624
The “System.IO.StreamReader” class ................................................................................ 626
The “System.IO.StreamReader” class - Example ............................................................... 627

C#.NET – Console – ADO.NET ................................................................................................... 629


Database Basics .................................................................................................................. 629
Introduction to ADO.NET ................................................................................................... 631
List of pre-defined classes in ADO.NET .............................................................................. 631
ADO.NET – “SqlConnection” class ...................................................................................... 632
SqlConnection – Windows Authentication – Example....................................................... 636
SqlConnection – SQL Server Authentication – Example .................................................... 639
The "SqlCommand" class in ADO.NET ................................................................................ 642
ADO.NET - ExecuteScalar ................................................................................................... 646
SqlCommand – ExecuteScalar – Example .......................................................................... 647
SqlCommand – ExecuteScalar – Example 2 ....................................................................... 650
ADO.NET – Connection Oriented Model – Introduction.................................................... 653

D. Harsha Vardhan (.NET Expert) P a g e 16 | 1583


C#.NET 8.0

The "SqlDataReader" class in ADO.NET ............................................................................. 654


ADO.NET – Connection Oriented Model ............................................................................ 656
ADO.NET Connection Oriented Model – Single Record – Example ................................... 657
ADO.NET Connection Oriented Model – Multiple Records – Example.............................. 661
The "SqlParameter" class in ADO.NET ............................................................................... 665
ADO.NET Connection Oriented Model – SqlParameter – Example ................................... 668
ADO.NET Disconnected Model........................................................................................... 672
The “SqlDataAdapter” class ............................................................................................... 673
The “DataSet” class ............................................................................................................ 674
DataSet - Example .............................................................................................................. 674
ADO.NET Disconnected Model – Example ......................................................................... 679
ADO.NET Disconnected Model – Multiple Tables - Example ............................................. 683
ADO.NET Disconnected Model – Joins - Example .............................................................. 688
ADO.NET Non Query - Insertion – Example ....................................................................... 692
ADO.NET Non-Query - Updation – Example ...................................................................... 695
ADO.NET Non-Query - Deletion – Example........................................................................ 698
ADO.NET Non Query – Insertion – With SqlParameter – Example .................................... 701
ADO.NET Non-Query – Updation – With SqlParameter – Example ................................... 705
ADO.NET Non-Query – Deletion – With SqlParameter – Example .................................... 709
Stored Procedures Calling in ADO.NET .............................................................................. 712
ADO.NET Non Query – Insertion – With Stored Procedures – Example............................ 713
ADO.NET Non Query – Updation – With Stored Procedures – Example ........................... 717
ADO.NET Non Query – Deletion – With Stored Procedures – Example ............................ 721
ADO.NET - Transactions ..................................................................................................... 725
ADO.NET – Transactions - Example .................................................................................... 726
The "OleDb" namespace in ADO.NET ................................................................................ 730
Connection Strings in ADO.NET.......................................................................................... 731
ADO.NET – Oracle - Example .............................................................................................. 732
ADO.NET – MS Access - Example ....................................................................................... 743
ADO.NET – MS Excel - Example .......................................................................................... 755
ADO.NET – SQL Server to Oracle - Example ....................................................................... 764

D. Harsha Vardhan (.NET Expert) P a g e 17 | 1583


C#.NET 8.0

ADO.NET – SQL Server to MS Excel - Example ................................................................... 771


ADO.NET – Oracle to SQL Server - Example ....................................................................... 779
ADO.NET – Excel to SQL Server - Example ......................................................................... 786
ADO.NET – SQL Server to File - Example ............................................................................ 794
ADO.NET – File to SQL Server - Example ............................................................................ 799
The "SqlCommandBuilder" class in ADO.NET .................................................................... 804
ADO.NET – SqlCommandBuilder – DataSet – Insertion - Example .................................... 805
ADO.NET – SqlCommandBuilder – DataSet – Updation - Example.................................... 809
ADO.NET – SqlCommandBuilder – DataSet – Deletion - Example ..................................... 813
N-Tier Architecture............................................................................................................. 817
N-Tier Architecture - Example ............................................................................................ 817
LINQ to SQL ........................................................................................................................ 825
LINQ to SQL - Example........................................................................................................ 826

C#.NET – Console – Entity Framework ..................................................................................831


Intro to ADO.NET Entity Framework .................................................................................. 831
Entity Framework - Example .............................................................................................. 834
Entity Framework – FirstOrDefault - Example ................................................................... 839
Entity Framework – Insertion - Example ............................................................................ 844
Entity Framework – Updation - Example ........................................................................... 849
Entity Framework – Deletion - Example ............................................................................ 854

C#.NET – Windows Forms Applications ................................................................................858


Introduction to Windows Forms Applications ................................................................... 858
The “System.Windows.Forms.Form” class ........................................................................ 859
Programming Model of Windows Form............................................................................. 860
Windows Forms Application – First Example ..................................................................... 861
Form Constructor - Example .............................................................................................. 863
Properties of “System.Windows.Forms.Form” class ......................................................... 865
“System.Windows.Forms.Form. Text” property - Example ............................................... 867
“System.Windows.Forms.Form. ShowIcon” property - Example ...................................... 869
“System.Windows.Forms.Form. ShowInTaskBar” property -Example .............................. 871

D. Harsha Vardhan (.NET Expert) P a g e 18 | 1583


C#.NET 8.0

“System.Windows.Forms.Form. MinimizeBox” property - Example ................................. 872


“System.Windows.Forms.Form. MaximizeBox” property - Example ................................ 874
“System.Windows.Forms.Form. ControlBox” property - Example .................................... 876
“System.Windows.Forms.Form. TopMost” property - Example ....................................... 877
“System.Windows.Forms.Form. WindowState” property –Example ................................ 879
“System.Windows.Forms.Form. FormBorderStyle” property – Example.......................... 880
“System.Windows.Forms.Form. Cursor” property - Example ........................................... 882
“System.Windows.Forms.Form. BackColor” property - Example ...................................... 884
“System.Windows.Forms.Form. BackgroundImage” property – Example ........................ 885
“System.Windows.Forms.Form. Size” property - Example................................................ 887
“System.Windows.Forms.Form. Location” property - Example ........................................ 889
“System.Windows.Forms.Form. Icon” property - Example ............................................... 890
Events of “System.Windows.Forms.Form” class ............................................................... 892
“System.Windows.Forms.Form. Load” event - Example ................................................... 893
“System.Windows.Forms.Form. Shown” event - Example ................................................ 896
“System.Windows.Forms.Form. Click” event - Example ................................................... 897
“System.Windows.Forms.Form. DoubleClick” event - Example ........................................ 899
“System.Windows.Forms.Form.MouseClick” event - Example ......................................... 901
“System.Windows.Forms.Form. MouseMove” event - Example ...................................... 903
“System.Windows.Forms.Form. KeyPress” event - Example............................................. 904
“System.Windows.Forms.Form. FormClosing” event - Example ....................................... 906
“System.Windows.Forms.Form. FormClosing” event - Example 2 .................................... 908
Methods of “System.Windows.Forms.Form” class............................................................ 910
“System.Windows.Forms.Form. Hide” method - Example ................................................ 911
“System.Windows.Forms.Form .Show” method - Example .............................................. 913
“System.Windows.Forms.Form. Close” method - Example............................................... 915
Introduction to Windows Forms Controls ......................................................................... 917
“System.Windows.Forms.Label” class ............................................................................... 919
“System.Windows.Forms.Label” class - Example .............................................................. 922
“System.Windows.Forms. Button” class ............................................................................ 925
“System.Windows.Forms. Button” class - Example ........................................................... 929

D. Harsha Vardhan (.NET Expert) P a g e 19 | 1583


C#.NET 8.0

“System.Windows.Forms. Button” class – with Image - Example ..................................... 932


“System.Windows.Forms. Button” class – with Label - Example ...................................... 934
“System.Windows.Forms. TextBox” class .......................................................................... 938
“System.Windows.Forms. TextBox” class - Example ......................................................... 943
“System.Windows.Forms. TextBox” class – With AutoComplete - Example ..................... 947
“System.Windows.Forms. TextBox” class – With AutoComplete – Example 2 ................. 949
“System.Windows.Forms. TextBox” class – With KeyPress – Example ............................. 952
“System.Windows.Forms. TextBox” class – With KeyPress – Example 2 .......................... 955
“System.Windows.Forms. TextBox” class – With Enter and Leave – Example.................. 957
“System.Windows.Forms. TextBox” class – With TabIndex – Example ............................. 961
“System.Windows.Forms. TextBox” class – Math – Example ............................................ 965
“System.Windows.Forms. NumericUpDown” class ........................................................... 970
“System.Windows.Forms. NumericUpDown” class – Example ......................................... 973
“System.Windows.Forms. DateTimePicker” class ............................................................. 976
“System.Windows.Forms. DateTimePicker” class – Example ............................................ 980
“System.Windows.Forms. MonthCalendar” class ............................................................. 983
“System.Windows.Forms. MonthCalendar” class – Example ............................................ 987
“System.Windows.Forms. ToolTip” class ........................................................................... 991
“System.Windows.Forms. ToolTip” class – Example ......................................................... 993
“System.Windows.Forms. ErrorProvider” class ................................................................. 995
“System.Windows.Forms. ErrorProvider” class – Example ............................................... 997
“System.Text. RegularExpressions. Regex” class ............................................................. 1000
“System.Text. RegularExpressions. Regex” class – Example............................................ 1001
“System.Windows.Forms. MaskedTextBox” class ........................................................... 1005
“System.Windows.Forms. MaskedTextBox” class - Example .......................................... 1008
“System.Windows.Forms. CheckBox” class ..................................................................... 1011
“System.Windows.Forms. CheckBox” class - Example .................................................... 1014
“System.Windows.Forms. RadioButton” class................................................................. 1016
“System.Windows.Forms. RadioButton” class - Example ................................................ 1019
“System.Windows.Forms. ComboBox” class ................................................................... 1023
“System.Windows.Forms. ComboBox” class - Example .................................................. 1026

D. Harsha Vardhan (.NET Expert) P a g e 20 | 1583


C#.NET 8.0

“Cascading ComboBox” - Example ................................................................................... 1029


“System.Windows.Forms. ListBox” class ......................................................................... 1032
“System.Windows.Forms. ListBox” class - Example......................................................... 1035
“System.Windows.Forms. CheckedListBox” class............................................................ 1038
“System.Windows.Forms. CheckedListBox” class – Example .......................................... 1041
“System.Windows.Forms. TreeView” class...................................................................... 1044
“System.Windows.Forms. TreeView” class - Example ..................................................... 1049
The “System.Windows.Forms. PictureBox” class ............................................................ 1052
“System.Windows.Forms. PIctureBox” class - Example .................................................. 1055
“System.Windows.Forms. PIctureBox” class – Example 2 ............................................... 1057
The “System.Windows.Forms. Panel” class ..................................................................... 1061
“System.Windows.Forms. Panel” class - Example ........................................................... 1063
The “System.Windows.Forms. GroupBox” class .............................................................. 1066
“System.Windows.Forms. GroupBox” class - Example .................................................... 1069
The “System.Windows.Forms. SplitContainer” class ....................................................... 1072
“System.Windows.Forms. SplitContainer” class - Example ............................................. 1075
The “System.Windows.Forms. TabControl” class ............................................................ 1077
“System.Windows.Forms. TabControl” class - Example .................................................. 1080
The “System.Windows.Forms. FlowLayoutPanel” class .................................................. 1083
“System.Windows.Forms. FlowLayoutPanel” class - Example ........................................ 1086
“System.Windows.Forms. LinkLabel” class ...................................................................... 1088
“System.Windows.Forms. LinkLabel” class - Example ..................................................... 1091
“System.Windows.Forms. WebBrowser” class ................................................................ 1094
“System.Windows.Forms. WebBrowser” class - Example ............................................... 1096
“System.Windows.Forms.Timer” class ............................................................................ 1099
“System.Windows.Forms. Timer” class - Example........................................................... 1101
“System.Windows.Forms.Timer” class – with Time - Example....................................... 1104
“System.Windows.Forms.Timer” class – with Counter - Example.................................. 1106
“System.Windows.Forms.Timer” class – with Slide Show - Example ............................. 1108
“System.Windows.Forms. ProgressBar” class ................................................................. 1112
“System.Windows.Forms. ProgressBar” class - Example................................................. 1115

D. Harsha Vardhan (.NET Expert) P a g e 21 | 1583


C#.NET 8.0

“System.Windows.Forms. NotifyIcon” class .................................................................... 1118


“System.Windows.Forms. NotifyIcon” class - Example ................................................... 1120
Popup Boxes ..................................................................................................................... 1123
PopupBoxes - Example ..................................................................................................... 1123
“System.Windows.Forms. ColorDialog” class .................................................................. 1130
“System.Windows.Forms. ColorDialog” class - Example ................................................. 1131
“System.Windows.Forms. FontDialog” class ................................................................... 1135
“System.Windows.Forms. FontDialog” class - Example................................................... 1137
“System.Windows.Forms. FolderBrowserDialog” class ................................................... 1140
“System.Windows.Forms. FolderBrowserDialog” class - Example .................................. 1143
“System.Windows.Forms. OpenFileDialog” class ............................................................ 1146
“System.Windows.Forms. OpenFileDialog” class - Example ........................................... 1148
“System.Windows.Forms. SaveFileDialog” class.............................................................. 1152
“System.Windows.Forms. SaveFileDialog” class - Example ............................................. 1154
“System.Windows.Forms. MenuStrip” class .................................................................... 1158
“System.Windows.Forms. MenuStrip” class - Example ................................................... 1163
“System.Windows.Forms. ContextMenuStrip” class ....................................................... 1167
“System.Windows.Forms. ContextMenuStrip” class - Example ...................................... 1170
“System.Windows.Forms. ToolStrip” class ...................................................................... 1174
“System.Windows.Forms. ToolStrip” class - Example ..................................................... 1178
“System.Windows.Forms. StatusStrip” class ................................................................... 1183
“System.Windows.Forms. StatusStrip” class - Example .................................................. 1187
“System.Windows.Forms. RichTextBox” class ................................................................. 1190
“System.Windows.Forms. RichTextBox” class - Example ................................................ 1195
User Controls .................................................................................................................... 1208
User Controls - Example ................................................................................................... 1209
Windows Forms Control Library....................................................................................... 1214
Windows Forms Control Library - Example ...................................................................... 1214
“System.Net.Mail.SmtpClient” class ................................................................................ 1220
“System.Net.Mail.SmtpClient” class - Example ............................................................... 1221
Multi-Threading................................................................................................................ 1225

D. Harsha Vardhan (.NET Expert) P a g e 22 | 1583


C#.NET 8.0

Multi Threading - Example ............................................................................................... 1229


Task Parallel Library.......................................................................................................... 1231
Task Parallel Library - Example ......................................................................................... 1233
Windows Services............................................................................................................. 1236
Windows Services - Example ............................................................................................ 1237

C#.NET – WinForms – System.IO Namespace................................................................... 1242


The “System.IO.FileInfo” class - Example......................................................................... 1242
The “System.IO.DirectoryInfo” class - Example ............................................................... 1246
The “System.IO.Directory” class - Example...................................................................... 1252
The “System.IO.File” class - Example ............................................................................... 1255
The “System.IO.StreamWriter” class - Example .............................................................. 1260
The “System.IO.StreamReader” class - Example ............................................................. 1263

C#.NET – WinForms – ADO.NET ..............................................................................................1267


SqlConnection – Windows Authentication – Example..................................................... 1267
SqlConnection – SQL Server Authentication – Example .................................................. 1270
SqlCommand – ExecuteScalar – Example ........................................................................ 1274
SqlCommand – ExecuteScalar – Example 2 ..................................................................... 1277
ADO.NET Connection Oriented Model – Single Record – Example ................................. 1281
ADO.NET Connection Oriented Model – Multiple Records – Example............................ 1285
ADO.NET Connection Oriented Model – Multiple Records - Label – Example ................ 1290
ADO.NET Connection Oriented Model – SqlParameter – Example ................................. 1294
ADO.NET Connection Oriented Model – SqlParameter – ComboBox – Example............ 1299
DataSet - Example ............................................................................................................ 1305
ADO.NET Disconnected Model – Example ....................................................................... 1311
ADO.NET Disconnected Model – Multiple Tables - Example ........................................... 1316
ADO.NET Disconnected Model – Joins - Example ............................................................ 1322
ADO.NET Disconnected Model – Record Navigations - Example .................................... 1327
ADO.NET Disconnected Model – ComboBox - Example .................................................. 1334
ADO.NET Disconnected Model – ComboBox - DataSource - Example ............................ 1340
ADO.NET Disconnected Model – DataGridView - Example ............................................. 1347

D. Harsha Vardhan (.NET Expert) P a g e 23 | 1583


C#.NET 8.0

ADO.NET Disconnected Model – DataGridView - SqlCommandBuilder - Example ......... 1350


ADO.NET Disconnected Model – Master – Child – Example ........................................... 1354
ADO.NET Disconnected Model – Cascading ComboBox – Example ................................ 1360
ADO.NET Non Query - Insertion – Example ..................................................................... 1366
ADO.NET Non Query - Updation – Example..................................................................... 1369
ADO.NET Non Query - Deletion – Example ...................................................................... 1372
ADO.NET Non Query – Insertion – With SqlParameter – Example .................................. 1376
ADO.NET Non Query – Updation – With SqlParameter – Example ................................. 1381
ADO.NET Non Query – Deletion – With SqlParameter – Example .................................. 1386
ADO.NET Non Query – Insertion – With Stored Procedures – Example.......................... 1390
ADO.NET Non Query – Updation – With Stored Procedures – Example ......................... 1395
ADO.NET Non Query – Deletion – With Stored Procedures – Example .......................... 1401
ADO.NET Disconnected Model – ComboBox – Stored Procedures – Example................ 1405
ADO.NET Disconnected Model – Updation with ComboBox - Example .......................... 1411
ADO.NET – CRUD (Create, Retrieve, Update, Delete) - Example ..................................... 1418
ADO.NET – Registration Form - Example ......................................................................... 1432
ADO.NET – Login Form - Example .................................................................................... 1439
ADO.NET – Transactions - Example .................................................................................. 1445
ADO.NET – Oracle - Example ............................................................................................ 1449
ADO.NET – MS Access - Example ..................................................................................... 1461
ADO.NET – MS Excel - Example ........................................................................................ 1475
ADO.NET – SQL Server to Oracle - Example ..................................................................... 1484
ADO.NET – SQL Server to MS Excel - Example ................................................................. 1491
ADO.NET – Oracle to SQL Server - Example ..................................................................... 1500
ADO.NET – Excel to SQL Server - Example ....................................................................... 1508
ADO.NET – SQL Server to File - Example .......................................................................... 1516
ADO.NET – File to SQL Server - Example .......................................................................... 1522
ADO.NET – SqlCommandBuilder – DataSet – Insertion - Example .................................. 1528
ADO.NET – SqlCommandBuilder – DataSet – Updation - Example.................................. 1533
ADO.NET – SqlCommandBuilder – DataSet – Deletion - Example ................................... 1538
N-Tier Architecture - Example .......................................................................................... 1542

D. Harsha Vardhan (.NET Expert) P a g e 24 | 1583


C#.NET 8.0

LINQ to SQL - Example...................................................................................................... 1551

C#.NET – WinForms – Entity Framework ........................................................................... 1559


Entity Framework - Example ............................................................................................ 1559
Entity Framework – Insertion - Example .......................................................................... 1565
Entity Framework – Updation - Example ......................................................................... 1571
Entity Framework – Deletion - Example .......................................................................... 1577

D. Harsha Vardhan (.NET Expert) P a g e 25 | 1583


C#.NET 8.0

1
.NET Fundamentals

Introduction to .NET

What is .NET?

• .NET is an “application development platform”, which is used to develop desktop, web and mobile applications.

• “Application” is a program (collection of instructions) that can run based on the operating
system.

• “Application Development” is a process of creating new applications based on the client’s


requirements.

• “Application Development Platform” is a software tool, based on which you can develop
applications.

• .NET is developed by Microsoft Corporation in 2002.

• “NET” is named to mean “Internet Age” applications; it has not abbreviation.

Parts of .NET

• .NET is mainly divided into 3 parts:

D. Harsha Vardhan (.NET Expert) P a g e 26 | 1583


C#.NET 8.0

1. C#.NET (C Sharp .NET)

2. ASP.NET (Active Server Pages .NET)

3. Xamarin.NET

1. C#.NET

• Covers language basics.

• It is used to develop “Stand-alone applications” that runs based on the single

machine.

• Ex: Calculator, Bill Generation Applications etc.

2. ASP.NET

• Covers server side programming.

• It is used to develop “Web applications” that runs based on “Client-server

architecture”.

3. Xamarin.NET

• Covers mobile programming.

• It is used to develop “Mobile applications” that runs based on “Mobile devices”.

History of .NET

History of .NET

• 1997: Microsoft wants to create a better programming language to develop standalone


and client-server applications. Microsoft team (led by Anders Hejlsberg, founder of Turbo
Pascal) has started developing the new language.

D. Harsha Vardhan (.NET Expert) P a g e 27 | 1583


C#.NET 8.0

• 1998: Microsoft has completed developing the new language and named it as Simple
Managed C (SMC).

• 1999: Microsoft renamed “SMS” as “C#” and wants to integrate C#, ASP. They named the
integrated development platform as “NGWS” (Next Generation Windows Services).

• 2000: Microsoft renamed “NGWS” as “.NET” (Network-based). Microsoft announced


“.NET” in July 2000.

• 2001: Microsoft has integrated C#.NET and ASP.NET in “.NET”.

• 2002: .NET 1.0

• 2003: .NET 1.1

• 2005: .NET 2.0

• 2006: .NET 3.0

• 2007: .NET 3.5

• 2010: .NET 4.0

• 2012: .NET 4.5

• 2013: .NET 4.5.1

• 2014: .NET 4.5.2

• 2015: .NET 4.6

• 2015: .NET 4.6.1

• 2016: .NET 4.6.2

• 2017: .NET 4.7

• 2017: .NET 4.7.1

• 2018: .NET 4.7.2

• 2019: .NET 4.8

D. Harsha Vardhan (.NET Expert) P a g e 28 | 1583


C#.NET 8.0

Versions of .NET

Sl. .NET Framework Year of Concepts


No release
1 .NET Framework 1.0 2002 Console Apps,
Language Fundamentals,
OOP,
WinForms,
Web Forms,
ADO.NET
2 .NET Framework 1.1 2003 ASP.NET Security
3 .NET Framework 2.0 2005 Improved web controls,
Data controls, Themes and skins,
Master pages,
Partial classes, Nullable types,
Anonymous methods, Generics
4 .NET Framework 3.0 2006 WPF
WCF
5 .NET Framework 3.5 2007 LINQ
ASP.NET AJAX
6 .NET Framework 4.0 2010 ADO.NET Entity Framework
Task Parallel Library
ASP.NET Web Pages
ASP.NET MVC
7 .NET Framework 4.5 2012 Open Authentication
ASP.NET Web API
ASP.NET Bundles and Minification
8 .NET Framework 4.5.1 2013 Async and Await
9 .NET Framework 4.5.2 2014 Bug fixes
10 .NET Framework 4.6 2015 .NET Core
ASP.NET Core
11 .NET Framework 4.6.1 2015 Spell Check for WPF
12 .NET Framework 4.6.2 2016 Soft keyboard support for WPF
13 .NET Framework 4.7 2017 Print API for WPF
14 .NET Framework 4.8 2019 Performance and Security Updates

D. Harsha Vardhan (.NET Expert) P a g e 29 | 1583


C#.NET 8.0

CIL and CLR

Execution Model of .NET Programs

Steps:
1. Source Code: The source code of the program is written in “.cs” file.

2. Compilation Process: “CSC” (C Sharp Compiler) compiles (converts) the program from

“C#.NET” (programmer understandable representation) to “MSIL (Microsoft Intermediate

Language)” (also called as “byte code”). The “MSIL code” will be saved in “.exe” file. This

D. Harsha Vardhan (.NET Expert) P a g e 30 | 1583


C#.NET 8.0

EXE file can’t execute directly. The MSIL is neither understandable by the programmer, nor

by operating system.

3. Execution Process: CLR (Common Language Runtime) converts the program from MSIL

language at “EXE file” to “native machine language” (based on the current operating

system). Operating System executes the “native machine language”. Then we will get

output.

CIL (Common Intermediate Language) or MSIL

▪ CIL or MSIL (Microsoft Intermediate Language) is the intermediate language, developed by

Microsoft Corporation, for .NET.

▪ The .net programs are converted into “MSIL language” first; and then converted into “native

machine language”.

▪ The MSIL code will be stored in "EXE" file. Ex: filename.exe. The “native machine language”

code will not be saved in any file, it directly runs.

▪ Once the code is converted into MSIL, it doesn't matter in which .net language it is originally

developed. So for all .net languages, we can have a common runtime engine called "CLR".

CLR (Common Language Runtime)

▪ CLR stands for “Common Language Runtime”.

▪ CLR is the “Execution Engine” or “Execution Environment” of .NET.

▪ To run any type of .net program (app), CLR must be installed in the computer.

▪ CLR will be started automatically when the .net application execution starts. CLR performs

essential tasks internally, while running any .net application.

▪ Without CLR, we can’t run any .net program.

▪ CLR reads the “MSIL code” from the EXE file, converts the same into “native machine code”,

gives the same to the operating system and then operating system executes the native

D. Harsha Vardhan (.NET Expert) P a g e 31 | 1583


C#.NET 8.0

machine code; then the user gets the output. So CLR is helps the operating system while

executing the .net program.

▪ CLR will be installed automatically as a part of “.NET Framework” software. CLR must be

installed in both developer’s machine and user’s machine.

Sub Components of CLR

▪ CLR has the following inner components (sub components).

1. Memory Manager: “Memory Manager” is a sub component in CLR, which allocates memory

(in RAM) for the variables and objects in the program.

2. Garbage Collector: “Garbage Collector” is a sub component in CLR, which deletes the

variables and objects that are created during the program, automatically at the end of the

program execution.

3. Class Loader: “Class Loader” is a sub component in CLR, which loads a class on-demand.

When we try to access a class in the program for the first time, then the “Class Loader”

searches for the class in the entire program, loads the class into the memory, and it passes

the class to JIT compiler. That means if we don’t call a class, it will not be loaded into

memory. This avoids un-necessary loading of the classes, if we don’t require them. So it

improves performance.

4. JIT (Just-In-Time) Compiler: “JIT Compiler” is a sub component in CLR, which converts the

“MSIL code” into “native machine language” (based on current operating system).

5. Thread Manager: “Thread Manager” is a sub component in CLR, which manages the

threads of the program. It gives necessary instructions to the processor, which thread is to

be executed when. A thread is a "part of the program" or "background work".

D. Harsha Vardhan (.NET Expert) P a g e 32 | 1583


C#.NET 8.0

6. Exception Manager: “Exception Manager” is a sub component in CLR, which passes

necessary instructions to the operating system, which code should be executed when an

exception (runtime error) occurs while executing the program.

7. Security Manager: “Security Manager” is a sub component in CLR, which takes care about

different types of security in .net such as windows authentication, forms authentication,

open authentication etc.

D. Harsha Vardhan (.NET Expert) P a g e 33 | 1583


C#.NET 8.0

.NET Framework Architecture

What is .NET Framework

• It is the “Software Development Kit (SDK)”, which contains many components such as CIL,

CLR, FCL, CLS, which is used to develop & run the .net applications.

• It should be installed in both developer system and user system.

• .NET Framework download link:

https://www.microsoft.com/en-us/download/details.aspx?id=55167

System Requirements of .NET Framework:

Software / Hardware Minimum Recommended


Requirement
Processor 1.6 Ghz 2.3 Ghz or higher
RAM 1 GB 2 GB or higher
Hard disk free space on 2 GB 4 GB or higher
C: drive
Operating System Windows 7 + Service Pack 1 Windows 10

Windows 8

Windows 8.1

Windows 10

D. Harsha Vardhan (.NET Expert) P a g e 34 | 1583


C#.NET 8.0

.NET Framework Architecture

• “.NET framework” is divided as several components.

• “.NET Framework Architecture” explains the list of components of .NET Framework, and

how they are arranged internally.

Explanation:

• "Windows" operating system works based on "processor".

• "CLR" works based on "Windows Operating System".

• "BCL" works based on "CLR".

• "ADO.NET" works based on "BCL".

• "WinForms", "ASP.NET", and “Other Frameworks” work based on "ADO.NET" and "BCL".

• "CLS" is created based on "WinForms", "ASP.NET" and “Other Frameworks”.

• "C#.NET", "VB.NET", "Other Languages" are developed based on "CLS".

• Finally, the programmers are writing the programs by using the languages called “C#.NET,

“VB.NET” etc.

D. Harsha Vardhan (.NET Expert) P a g e 35 | 1583


C#.NET 8.0

CLS and CTS

CLS (Common Language Specification)

▪ “CLS” is the set of rules, based on which all .net languages (C#.NET, VB.NET, VC++.NET etc.)

are developed.

▪ The common rules are about literals, operators, identifiers, data types, type conversion, object

oriented programming etc.

CTS (Common Type System)

▪ “CTS” is a set common data types, based on which, the data types of all .net languages

(C#.NET, VB.NET, VC++.NET etc.) are developed.

▪ Thus, we achieve the uniform data types among all .net languages.

▪ The following is the list of data types of CTS:

1. SByte

2. Byte

3. Short

4. UShort

5. Int32

6. UInt32

7. Int64

8. UInt64

9. Single

10. Double

11. Decimal

12. Char

13. String

14. Boolean

D. Harsha Vardhan (.NET Expert) P a g e 36 | 1583


C#.NET 8.0

FCL and BCL

FCL (Framework Class Library)

▪ .NET provides a set of classes and interfaces, based on which we can develop .net applications.

▪ The “DLL (Dynamic Link Library)” file is a collection of namespaces; Namespace is a collection

of classes and interfaces.

▪ FCL is divided into the following parts:

1. BCL: BCL is a set of classes and interfaces, which can be used in all types of applications.

2. WinForms: This is a set of classes and interfaces, which can be used only in windows

applications.

3. ASP.NET: This is a set of classes and interfaces, which can be used only in web applications.

4. ADO.NET: This is a set of classes and interfaces, which can be used in all types of

applications for connecting to databases.

D. Harsha Vardhan (.NET Expert) P a g e 37 | 1583


C#.NET 8.0

Introduction to Visual Studio

What is Visual Studio

• Visual Studio is the “IDE” (Integrated Development Environment), where you can write all

types of .net programs (C#.NET, ASP.NET).

• It provides advantages such as syntax highlighting, intellisense, deployment etc.

Versions of Visual Studio

Visual Studio Version Year of Supported Operating Systems Supported


Release .NET
Framework
Versions
Visual Studio 2002 (7.0) 2002 Windows 2000 .NET 1.0
Windows XP
Visual Studio 2003 (7.1) 2003 Windows 2000 .NET 1.1
Windows XP
Visual Studio 2005 (8.0) 2005 Windows 2000 .NET 2.0
Windows XP
Visual Studio 2008 (9.0) 2007 Windows 2000 .NET 2.0
Windows XP .NET 3.0
Windows 7 .NET 3.5
Visual Studio 2010 (10.0) 2010 Windows XP + Service Pack 3 .NET 2.0
Windows 7 .NET 3.0
.NET 3.5
.NET 4.0
Visual Studio 2012 (11.0) 2012 Windows 7 .NET 2.0
Windows 8.1 .NET 3.0
Windows 10 .NET 3.5
.NET 4.0
.NET 4.5
Visual Studio 2013 (12.0) 2013 Windows 7 + Service Pack 1 .NET 2.0
Windows 8.1 .NET 3.0

D. Harsha Vardhan (.NET Expert) P a g e 38 | 1583


C#.NET 8.0

Windows 10 .NET 3.5


.NET 4.0
.NET 4.5
.NET 4.5.1
Visual Studio 2015 (14.0) 2015 Windows 7 + Service Pack 1 .NET 2.0
Windows 8.1 .NET 3.0
Windows 10 .NET 3.5
.NET 4.0
.NET 4.5
.NET 4.5.1
.NET 4.5.2
.NET 4.6
.NET 4.6.1
.NET 4.6.2
Visual Studio 2017 (15.0) 2017 Windows 7 + Service Pack 1 .NET 2.0
Windows 8.1 .NET 3.0
Windows 10 .NET 3.5
.NET 4.0
.NET 4.5
.NET 4.5.1
.NET 4.5.2
.NET 4.6
.NET 4.6.1
.NET 4.6.2
.NET 4.7
Visual Studio 2019

System Requirements of Visual Studio 2019:

Software / Hardware Minimum Recommended


Requirement
Processor 1.6 Ghz 2.3 Ghz or higher
RAM 2 GB 4 GB or higher
Hard disk free space on 10 GB 15 GB or higher

D. Harsha Vardhan (.NET Expert) P a g e 39 | 1583


C#.NET 8.0

C: drive
Operating System Windows 7 + Service Pack 1 Windows 10

Windows 8.1

Windows 10

Internet Explorer Internet Explorer 10 Internet Explorer 11 or above

Project

• Project is a folder, which is a “group of files”.

• A file contains code (program).

• When we compile the project, Visual Studio generates only one EXE file for the entire

project, which contains the compiled source code (in MSIL language) of all the files of the

same project.

Solution

• Solution is a folder, which is a “group of projects”.

File Types of .NET

• .NET supports the following file types:

File Extension Full form Description


.cs C# file A C# file contains the C#.NET program (source code).
.vb VB file A VB file contains the VB.NET program (source code).
.csproj C# Project A project is a collection of files.
The project file contains the list of all the files in the
current project.
.sln Solution A solution is a collection of projects.
The solution file contains the list of all the projects in
the current solution.

D. Harsha Vardhan (.NET Expert) P a g e 40 | 1583


C#.NET 8.0

.exe Executable file The EXE file contains the compiled source code of a
project. For every project, a separate EXE file will be
created.
.config Configuration File The configuration file contains the configuration
settings of a project.

Folder Structure of .NET Project in Visual Studio

• .NET program (project) should have the following folder structure.

• Every solution is a folder. Every project is folder.

Solution Folder
 Project Folder
o filename.cs
o App.config
o projectname.csproj
o bin\projectname.exe
 solutionname.sln

D. Harsha Vardhan (.NET Expert) P a g e 41 | 1583


C#.NET 8.0

Visual Studio - Installation

Steps to install “Visual Studio 2019”:

Go to http://www.visualstudio.com

Click on “Download Visual Studio” – “Community 2019”.

You will get “vs_community.exe” file.

Run “vs_community.exe” file.

Click on “Run”.

Click on “Continue”.

D. Harsha Vardhan (.NET Expert) P a g e 42 | 1583


C#.NET 8.0

Check the checkboxes “.NET desktop development” and “ASP.NET and web development”.

Click on “Install”.

D. Harsha Vardhan (.NET Expert) P a g e 43 | 1583


C#.NET 8.0

Wait for installation to be completed.

Click on “Restart”.

After restarting your system, go to “Start” > “Visual Studio 2019”.

D. Harsha Vardhan (.NET Expert) P a g e 44 | 1583


C#.NET 8.0

If you have Microsoft account already and click on “Sign in” and complete the login process.

If you don’t have Microsoft account, click on “Sign up” and complete the registration process.

Note: If you don’t want to login, click on “Not now, may be later”; but then Visual Studio expires in
30 days.

D. Harsha Vardhan (.NET Expert) P a g e 45 | 1583


C#.NET 8.0

If you click on “Sign up”, you will get the following page.

D. Harsha Vardhan (.NET Expert) P a g e 46 | 1583


C#.NET 8.0

Enter your email id and enter new password.

Click on “Next”.

D. Harsha Vardhan (.NET Expert) P a g e 47 | 1583


C#.NET 8.0

You will get a security code to your email. Login into your gmail, check the code that you have
received and enter it in this page.

After entering the security code, click on “Next”.

D. Harsha Vardhan (.NET Expert) P a g e 48 | 1583


C#.NET 8.0

If you get the above page, you have successfully registered.

D. Harsha Vardhan (.NET Expert) P a g e 49 | 1583


C#.NET 8.0

Now click on “Sign in” in Visual Studio and enter the email.

Enter the password.

D. Harsha Vardhan (.NET Expert) P a g e 50 | 1583


C#.NET 8.0

Click on “Sign in”.

D. Harsha Vardhan (.NET Expert) P a g e 51 | 1583


C#.NET 8.0

D. Harsha Vardhan (.NET Expert) P a g e 52 | 1583


C#.NET 8.0

Select “Development Settings” as “General”.

Select “color theme” as “Blue”.

Click on “Start Visual Studio”.

D. Harsha Vardhan (.NET Expert) P a g e 53 | 1583


C#.NET 8.0

Visual Studio Installation has been completed successfully.

D. Harsha Vardhan (.NET Expert) P a g e 54 | 1583


C#.NET 8.0

2
C#.NET – Language
Fundamentals

Introduction to C#.NET

What is C#.NET:

C#.NET is the .NET’s most popular programming language, which is used to create stand-alone
applications (console applications and windows applications, windows services) primarily.

• C#.NET is developed on basis of C, C++.

• C#.NET is an “Object Oriented Programming Language”.

• C#.NET is a case sensitive language.

• C#.NET is an advanced and matured language.

• C#.NET is a high-level programming language.

• C#.NET is a compiler-based language.

• C#.NET is a part of .NET Framework.

• C#.NET programs run based on the CLR (.NET run time environment).

D. Harsha Vardhan (.NET Expert) P a g e 55 | 1583


C#.NET 8.0

Versions of C#.NET

Sl. No C#.NET Version .NET Framework Version Year of release

1 C#.NET 1.0 .NET Framework 1.0 2002


2 C#.NET 1.1 .NET Framework 1.1 2003
3 C#.NET 2.0 .NET Framework 2.0 2005
4 C#.NET 3.0 .NET Framework 3.0 2006
5 C#.NET 3.5 .NET Framework 3.5 2007
6 C#.NET 4.0 .NET Framework 4.0 2010
7 C#.NET 5.0 .NET Framework 4.5 2012
8 C#.NET 5.1 .NET Framework 4.5.1 2013
9 C#.NET 5.2 .NET Framework 4.5.2 2014
10 C#.NET 6.0 .NET Framework 4.6 2015
11 C#.NET 7.0 .NET Framework 4.7 2017
12 C#.NET 8.0 .NET Framework 4.8 2019

Tokens of C#.NET

• In "C#.NET", we have to use the following tokens (parts of the language).

Sl. Token Description

No

1 Keywords abstract, as, base, bool, break, byte, case, catch, char, class, const, continue,

decimal, default, delegate, do, double, else, enum, event, false, finally, float,

for, foreach, goto, if, in, int, interface, internal, is, long, namespace, new,

null, object, out, override, private, protected, public, readonly, ref, return,

sbyte, sealed, short, sizeof, static, string, struct, switch, this, throw, true,

try, typeof, uint, ulong, ushort, using, virtual, void, while, async, await, from,

join, let, orderby, partial, set, get, value, var, where

2 Operators Any symbols such as +, -, *, /, %, =, == etc.

D. Harsha Vardhan (.NET Expert) P a g e 56 | 1583


C#.NET 8.0

3 Literals Fixed values are literals.

• Integer literals: Any number without decimal part. Ex: 10

• Floating-point literals: Any number with decimal part. Ex: 10.87

• Character literals: Any single character in single quotes. Ex: ‘A’.

The character can be alphabet, digit, space or special symbol.

• String literals: One or more characters in double quotes. Ex: “Abc

123$”

• Boolean literals: true / false

4 Identifiers Any user-defined names: abc

Naming Conventions for Identifiers

• Class names, Interface names, Namespace names, Structure names, Method names,

Property names: PascalCasing

• Local variables: camelCasing

• Public Fields: PascalCasing

• Private Fields: camelCasing with underscore ( _ )

Identifier Naming Rules

You must follow the below rules while giving name for identifier.

• Identifier names can’t be same as keyword.

• Identifier names should not have spaces.

• Identifier names should not have special characters.

• Duplicate identifier names not allowed.

D. Harsha Vardhan (.NET Expert) P a g e 57 | 1583


C#.NET 8.0

Console Applications - Introduction

What is Console Application?

• Console applications are the programs that run on “Command Prompt” window.

• Console applications support CUI (Character User Interface).

• In console applications, all the input and output will be in the form of characters only.

• Console applications are not user-friendly.

• Console applications are not used in real time, but good for learning programming basics

and OOP concepts.

Rules of Console Application

• Console application must have atleast one class; which is called as “Main class”.

• The “Main class” must contain atleast one method; which is called as “Main method”.

• The “main method” name should be “Main”; “M” is capital letter.

• When the program execution starts the “Main” method will be automatically executed.

Main method is the “starting point of the program execution”.

• The Main method should be “static” method, because it should be called without creating

any object for the class.

Syntax:
class classname
{
static void Main()
{
}
}

D. Harsha Vardhan (.NET Expert) P a g e 58 | 1583


C#.NET 8.0

Console Application - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “Project1”.

• Type the location as “C:\CSharp”.

• Type the solution name as “Solution1”.

• Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Sample
{
static void Main()
{
System.Console.Write("Hello World");
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 59 | 1583


C#.NET 8.0

Output

The “System.Console” class

The “System.Console” class


• C#.NET provides “System.Console” class to perform I/O operations in console applications.

• “System” is a namespace; “Console” is a class.

• The following are the important methods of “System.Console” class.

1. System.Console.Write()

2. System.Console.WriteLine()

3. System.Console.ReadKey()

4. System.Console.ReadLine()

5. System.Console.Clear()

1. System.Console.Write()

• This statement is used to display the given value on the command prompt window.

• After printing the value, the cursor will be kept in the same line.

• Syntax: System.Console.Write(value);

• Example: System.Console.Write(100);

D. Harsha Vardhan (.NET Expert) P a g e 60 | 1583


C#.NET 8.0

2. System.Console.WriteLine()

• This statement is used to display the given value on the command prompt window.

• After printing the value, the cursor will be automatically moved to the next line.

• Syntax: System.Console.WriteLine(value);

• Example: System.Console.WriteLine(100);

3. System.Console.ReadKey()

• This statement is used to wait until the user presses any key on the keyboard.

• Syntax: System.Console.ReadKey();

• Example: System.Console.ReadKey();

4. System.Console.ReadLine()

• This statement is used to accept a string value from keyboard.

• Syntax: System.Console.ReadLine();

• Example: System.Console.ReadLine();

5. System.Console.Clear()

• This statement is used to clear the screen.

• Syntax: System.Console.Clear();

• Example: System.Console.Clear();

D. Harsha Vardhan (.NET Expert) P a g e 61 | 1583


C#.NET 8.0

System.Console.WriteLine – Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “WriteLineExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “WriteLineExample”.

• Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
System.Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 62 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

System.Console.ReadKey – Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ReadKeyExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ReadKeyExample”.

• Click on OK.

• It shows “Program.cs” file automatically.

D. Harsha Vardhan (.NET Expert) P a g e 63 | 1583


C#.NET 8.0

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
//display message
System.Console.WriteLine("Hello");

//wait for pressing any key on the keyboard


System.Console.ReadKey();

//display message
System.Console.WriteLine("Hello");

//wait for pressing any key on the keyboard


System.Console.ReadKey();

//display message
System.Console.WriteLine("Hello");

//wait for pressing any key on the keyboard


System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 64 | 1583


C#.NET 8.0

Output

Press Enter.

Press Enter.

System.Console.Clear - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ClearExample”.

D. Harsha Vardhan (.NET Expert) P a g e 65 | 1583


C#.NET 8.0

• Type the location as “C:\CSharp”.

• Type the solution name as “ClearExample”.

• Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
//display message
System.Console.WriteLine("Hello");
//wait for pressing any key on the keyboard
System.Console.ReadKey();
//clear the screen
System.Console.Clear();
//display message
System.Console.WriteLine("how");
//wait for pressing any key on the keyboard
System.Console.ReadKey();
//clear the screen
System.Console.Clear();
//display message
System.Console.WriteLine("are you");
//wait for pressing any key on the keyboard
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 66 | 1583


C#.NET 8.0

Output

Press Enter.

Press Enter.

D. Harsha Vardhan (.NET Expert) P a g e 67 | 1583


C#.NET 8.0

Variables

Variables
• A variable is a named memory location in RAM, to store a particular type of value
temporarily while the program is running.

• All the variables stored in RAM (temporary memory).

• All the variables must be declared before its usage. While declaring variables, data type is
to be specified. Based on the data type, the amount of memory to be allocated will be
decided. Once a variable is declared, we can’t change the “variable name” or “variable’s data
type”.

• The variables memory will be allocated when the program execution starts; and all the
variables will be deleted (de-allocated) from memory automatically, at the end of the
program.

• A variable can store only one value. If you assign another value, the old value will be
overwritten.

• We can change the value of a variable any no. of times.

• Syntax to create a variable:

datatype variablename ;

• Syntax to set value into a variable:

variablename = value ;

• Syntax to get the value of a variable:

variablename

D. Harsha Vardhan (.NET Expert) P a g e 68 | 1583


C#.NET 8.0

Variables - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “VariablesExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “VariablesExample”.

• Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
//create a variable
int x;
//set value into the variable
x = 10;
//get the value of variable
System.Console.WriteLine(x);
//wait for pressing any key on the keyboard
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 69 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 70 | 1583


C#.NET 8.0

Data Types

Data Type
• A data type is a concept, which specifies the type of the data that is to be stored in a
variable.

Types of Data types

• Data types are two types:

I. Numerical data types

II. Non-numerical data types

Numerical Data Types

Sl. Data Description No. of Range Suitable to


No Type Bytes store

1 sbyte 8-bit signed 1 byte -128 to 127 Very small


integer positive or
negative
integers
2 byte 8-bit 1 byte 0 to 255 Very small
unsigned positive
integer integers
3 short 16-bit signed 2 bytes -32,768 to 32,767 Small positive
integer or negative
integers
4 ushort 16-bit 2 bytes 0 to 65,535 Small positive
unsigned integers
integer

D. Harsha Vardhan (.NET Expert) P a g e 71 | 1583


C#.NET 8.0

5 int 32-bit signed 4 bytes -2,147,483,648 to 2,147,483,647 Medium


integer positive or
negative
integers
6 uint 32-bit 4 bytes 0 to 4,294,967,295 Medium
unsigned positive
integer integers
7 long 64-bit signed 8 bytes -9,223,372,036,854,775,808 to Large positive
integer 9,223,372,036,854,770,000 or
negative
integers
8 ulong 64-bit 8 bytes 0 to 18,446,744,073,709,551,615 Large positive
unsigned integers
integer
9 float Signed 4 bytes -3.402823E+38 to 3.402823E+38 Small
floating- (Precision: 7 digits) floating-point
point numbers
number
10 double Signed 8 bytes -1.79769313486232E+308 to Medium
floating- 1.79769313486232E+308 floating-point
point (Precision: 15 digits) numbers
number

11 decimal Signed 16 -79228162514264337593543950335 Large


floating- bytes to 79228162514264337593543950335 floating-point
point (Precision: 28 digits) numbers
number

Default Numerical data types

• C# compiler automatically treats a “number without decimal part” as “int” data type, if it is
within the maximum limit of “int” data type.

D. Harsha Vardhan (.NET Expert) P a g e 72 | 1583


C#.NET 8.0

• C# compiler automatically treats a “number without decimal part” as “long” data type, if it
exceeds the limit of “int” data type.

• C# compiler automatically treats a number with decimal part as “double” data type.

Non-Numerical Data Types

Sl. Data Type Description Value format No. of Bytes


No

1 char To store single character ‘character’ 2 bytes

2 string To store one or more "string here" No. of characters * 2


characters.

Max: 2 billion characters

3 bool To store true / false values. true or false 1 bit

Numerical Data Types - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “NumericalDataTypesExample”.

• Type the location as “C:\CSharp”.

D. Harsha Vardhan (.NET Expert) P a g e 73 | 1583


C#.NET 8.0

• Type the solution name as “NumericalDataTypesExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variables for all numerical data types
sbyte a = 10;
byte b = 20;
short c = 30;
ushort d = 40;
int e = 50;
uint f = 60;
long g = 70;
ulong h = 80;
float i = 90.23F;
double j = 100.23489;
decimal k = 110.882932M;

//displays the values of all variables


System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(d);
System.Console.WriteLine(e);
System.Console.WriteLine(f);
System.Console.WriteLine(g);
System.Console.WriteLine(h);
System.Console.WriteLine(i);
System.Console.WriteLine(j);
System.Console.WriteLine(k);
System.Console.ReadKey();
}

D. Harsha Vardhan (.NET Expert) P a g e 74 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 75 | 1583


C#.NET 8.0

MinValue and MaxValue

NumericalDataType.MinValue
• This statement returns the minimum value of the specified numerical data type.

• Syntax: datatype.MinValue

• Ex: int.MinValue

NumericalDataType.MaxValue
• This statement returns the maximum value of the specified numerical data type.

• Syntax: datatype.MaxValue

• Ex: int.MaxValue

MinValue and MaxValue - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MinValueMaxValueExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MinValueMaxValueExample”.

D. Harsha Vardhan (.NET Expert) P a g e 76 | 1583


C#.NET 8.0

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//get the minimum value of "int" data type
int min = int.MinValue;

//get the maximum value of "int" data type


int max = int.MaxValue;

//display the min and max values


System.Console.WriteLine(min);
System.Console.WriteLine(max);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 77 | 1583


C#.NET 8.0

char - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “charExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “charExample”.

• Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
//create variable of "char" data type
char ch = 'A';
//display the value of the variable
System.Console.WriteLine(ch);
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 78 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

String

String
• String: A string is a group of characters.

• String literal should be written inside the double quotes.

• All the names are strings. Ex: person names, city names, country names etc.

• String may contain alphabets, numbers, spaces and also special symbols.

• Alpha-numerical values are also treated as strings. Ex: car number, phone number, bank
ifsc codes etc.

• Syntax to create a string variable:

o string variablename = "value";

D. Harsha Vardhan (.NET Expert) P a g e 79 | 1583


C#.NET 8.0

String - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “StringExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “StringExample”. Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
//create a variable
string s = "Hello 123 $#&";

//display the value of the variable


System.Console.WriteLine(s);
System.Console.WriteLine(s);
System.Console.WriteLine(s);

System.Console.ReadKey();
}

D. Harsha Vardhan (.NET Expert) P a g e 80 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Bool - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “boolExample”.

D. Harsha Vardhan (.NET Expert) P a g e 81 | 1583


C#.NET 8.0

• Type the location as “C:\CSharp”.

• Type the solution name as “boolExample”.

• Click on OK.

• It shows “Program.cs” file automatically.

• Type the following code for “Program.cs” file:

Program.cs
class Program
{
static void Main()
{
//create variable of "bool" data type
bool b = true;
//display the value of the variable
System.Console.WriteLine(b);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 82 | 1583


C#.NET 8.0

Operators

What is Operator:
• Operator is a symbol to perform an operation.

• An operator receives one or two operands and perform some operation & returns the
result.

• Types of operators:

1. Arithmetical Operators

2. Assignment Operators

3. Increment and Decrement Operators

4. Relational Operators

5. Logical Operators

6. Concatenation Operator

7. Conditional Operator

Arithmetical Operators
Arithmetical Operators

Sl. No Operator Description

1 + Addition

2 - Subtraction

3 * Multiplication

4 / Division

5 % Remainder

D. Harsha Vardhan (.NET Expert) P a g e 83 | 1583


C#.NET 8.0

Arithmetical Operators - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ArithmeticalOperatorsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ArithmeticalOperatorsExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create two variables of "double" data type
double a = 10, b = 3;

//addition
double c = a + b;

//subtraction
double d = a - b;

//multiplication
double e = a * b;

//division
double f = a / b;

D. Harsha Vardhan (.NET Expert) P a g e 84 | 1583


C#.NET 8.0

//remainder
double g = a % b;

//display all the values


System.Console.WriteLine(a); //Output: 10
System.Console.WriteLine(b); //Output: 3
System.Console.WriteLine(c); //Output: 13
System.Console.WriteLine(d); //Output: 7
System.Console.WriteLine(e); //Output: 30
System.Console.WriteLine(f); //Output: 3.3333333333
System.Console.WriteLine(g); //Output: 1

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 85 | 1583


C#.NET 8.0

Assignment Operators
Assignment Operators

Sl. No Operator Description

1 = Assigns to

2 += Add and assigns to

3 -= Subtract and assigns to

4 *= Multiply and assigns to

5 %= Remainder and assigns to

Assignment Operators - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “AssignmentOperatorsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “AssignmentOperatorsExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()

D. Harsha Vardhan (.NET Expert) P a g e 86 | 1583


C#.NET 8.0

{
//create two variables of "int" data type
int a = 100;
int b;
//get the value from "a" and set the same into "b"
b = a;
//display the values of "a" and "b"
System.Console.WriteLine(a); //Output: 100
System.Console.WriteLine(b); //Output: 100
//a = a + 10
a += 10;
System.Console.WriteLine(a); //Output: 110
//a = a - 10
a -= 10;
System.Console.WriteLine(a); //Output: 100
//a = a * 3
a *= 3;
System.Console.WriteLine(a); //Output: 300
//a = a / 3
a /= 3;
System.Console.WriteLine(a); //Output: 100
//a = a % 30
a %= 30;
System.Console.WriteLine(a); //Output: 10
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 87 | 1583


C#.NET 8.0

Output

Increment / Decrement Operators


Increment / Decrement Operators

Sl. No Operator Description

1 ++ Increment

2 -- Decrement

Increment / Decrement Operators - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “IncDecOperatorsExample”.

• Type the location as “C:\CSharp”.

D. Harsha Vardhan (.NET Expert) P a g e 88 | 1583


C#.NET 8.0

• Type the solution name as “IncDecOperatorsExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create a variable of "int" data type
int n = 10;
//display the value of "n"
System.Console.WriteLine(n); //Output: 10
//n = n + 1
n++;
System.Console.WriteLine(n); //Output: 11

//n = n - 1
n--;
System.Console.WriteLine(n); //Output: 10

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 89 | 1583


C#.NET 8.0

Output

Relational Operators
Relational Operators

Sl. No Operator Description

1 == Equal to

2 != Not equal to

3 < Less than

4 > Greater than

5 <= Less than or equal to

6 >= Greater than or equal to

Relational Operators - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

D. Harsha Vardhan (.NET Expert) P a g e 90 | 1583


C#.NET 8.0

• Type the project name as “RelationalOperatorsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “RelationalOperatorsExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create two variables of "long" data type
long x = 1000, y = 2000;

//check whether x and y are equal


bool b1 = (x == y);

//check whether x and y are not equal


bool b2 = (x != y);

//check whether x is less than y


bool b3 = (x < y);

//check whether x is greater than y


bool b4 = (x > y);

//check whether x is less than or equal to y


bool b5 = (x <= y);

//check whether x is greater than or equal to y


bool b6 = (x >= y);

System.Console.WriteLine(b1); //Output: false


System.Console.WriteLine(b2); //Output: true
System.Console.WriteLine(b3); //Output: true

D. Harsha Vardhan (.NET Expert) P a g e 91 | 1583


C#.NET 8.0

System.Console.WriteLine(b4); //Output: false


System.Console.WriteLine(b5); //Output: true
System.Console.WriteLine(b6); //Output: false

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Logical Operators
Logical Operators

Sl. No Operator Description

1 && And (Both conditions must be true)

2 || Or (Any one of the conditions must be true)

3 ! Not (Given condition will be reverse)

D. Harsha Vardhan (.NET Expert) P a g e 92 | 1583


C#.NET 8.0

Logical Operators - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”. Select “Console Application”.

• Type the project name as “LogicalOperatorsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “LogicalOperatorsExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create 3 variables of "int" data type
int a = 10, b = 20, c = 10;

//and
bool result1 = ((a == b) && (b > c));
System.Console.WriteLine(result1); //Output: false

//or
bool result2 = ((a == b) || (b > c));
System.Console.WriteLine(result2); //Output: true

//not

D. Harsha Vardhan (.NET Expert) P a g e 93 | 1583


C#.NET 8.0

bool result3 = !(a == b);


System.Console.WriteLine(result3); //Output: true

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Concatenation Operator
Concatenation Operator

Sl. No Operator Description

1 + Concatenation. It attaches two values and returns as a string.


The following cases, "+" operator is "concatenation operator".

• String + String

• String + Number

• Number + String

D. Harsha Vardhan (.NET Expert) P a g e 94 | 1583


C#.NET 8.0

Concatenation Operator - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ConcatenationOperatorExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ConcatenationOperatorExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create strings
string s1 = "peers";
string s2 = "tech";
string s3;

//concatenate s1 and s2 and store the result in s3


s3 = s1 + s2;

System.Console.WriteLine(s1); //Output: peers


System.Console.WriteLine(s2); //Output: tech
System.Console.WriteLine(s3); //Output: peeerstech
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 95 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Conditional Operator
Conditional Operator

Sl. Operator Description


No

1 (condition)? value1 : value2 Checks the given condition.

Returns the value1, if given condition is TRUE

Returns the value2, if the given condition is FALSE.

Conditional Operator - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 96 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “ConditionalOperatorExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ConditionalOperatorExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create a variable of "int" data type
int n = -100;

//check the condition; store "positive" if the condition is true; store


"negative" if the condition is false
string s = ( (n >= 0) ? "positive" : "negative");
System.Console.WriteLine(s); //Output: negative
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 97 | 1583


C#.NET 8.0

Control Statements

What are control statements?


• Control statements are used to control the “program execution flow”.
• That means these are used to “go forward” or “go backward” within the program.

Types of control statements:

 Conditional Control Statements

• If

• Switch-case

 Looping Control Statements

• While

• Do-While

• For

 Jumping Control Statements

• Break

• Continue

• Goto

D. Harsha Vardhan (.NET Expert) P a g e 98 | 1583


C#.NET 8.0

If
If

Sl. Control Syntax Description


No Statement

1 If if (condition) It executes the “if block” only if the


{ given condition is TRUE.
Your code here
It doesn’t execute anything if the given
}
condition is FALSE.

2 If-Else if (condition) It executes the “if block” if the given


{ condition is TRUE.
Your code here
It executes the “else block” if the given
}
condition is FALSE.
else
{
Your code here
}
3 Else-If if (condition) It executes the “if block”, if the “first
{ condition” is TRUE.
Your code here
It executes the "first else if block", if the
}
second condition is TRUE.
else if (condition)
It executes the "second else if block", if
{
the third condition is TRUE.
Your code here
} It executes the “else block” if all the
else if (condition) conditions are FALSE.
{
Your code here
}
else
{
Your code here
}
4 Nested If if (condition) If inside another if.
{

D. Harsha Vardhan (.NET Expert) P a g e 99 | 1583


C#.NET 8.0

if (condition)
{
Your code here
}
else
{
Your code here
}
}
else
{
if (condition)
{
Your code here
}
else
{
Your code here
}
}

D. Harsha Vardhan (.NET Expert) P a g e 100 | 1583


C#.NET 8.0

If - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “IfExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “IfExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variables
int n = 100;

//check whether n is equal to 100


if (n == 100)
{
System.Console.WriteLine("n is equal to 100");
}
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 101 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

If – Else - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “IfElseExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “IfElseExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variables

D. Harsha Vardhan (.NET Expert) P a g e 102 | 1583


C#.NET 8.0

int n = 150;

//check whether n is equal to 100


if (n == 100)
{
System.Console.WriteLine("n is equal to 100");
}
else
{
System.Console.WriteLine("n is not equal to 100");
}
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 103 | 1583


C#.NET 8.0

Else – If - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ElseIfExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ElseIfExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variables
int a = 10, b = 20;

//check which is the big number


if (a == b)
System.Console.WriteLine("a and b are equal");
else if (a > b)
System.Console.WriteLine("a is bigger than b");
else
System.Console.WriteLine("b is bigger than a");
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 104 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Nested If - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “NestedIfExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “NestedIfExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variables
int a = 150, b = 100;

D. Harsha Vardhan (.NET Expert) P a g e 105 | 1583


C#.NET 8.0

string msg;

//outer if
if (a >= b)
{
//inner if
if (a > b)
{
msg = "a is greater than b";
}
//"else" for "inner if"
else
{
msg = "a is equal to b";
}
}
//"else" for "outer if"
else
{
msg = "a is less than b";
}
System.Console.WriteLine(msg); //Output: a is greater than b
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 106 | 1583


C#.NET 8.0

Switch – Case
Switch-case

Sl. Control Syntax Description


No Statement

1 Switch-case switch (variable) It checks the variable’s


{ value whether it
case value1 : your code here ; break; matches with which
case value2 : your code here ; break; case & executes the
… corresponding code.
default: your code here ; break;
It executes the default
}
code if all cases are not
matched.

Switch – Case - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “SwitchCaseExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “SwitchCaseExample”.

• Click on OK.

Program.cs
class Program
{

D. Harsha Vardhan (.NET Expert) P a g e 107 | 1583


C#.NET 8.0

static void Main()


{
//create variables
int monthnumber = 7;
string monthname;

//check the value of monthnumber whether it matches with any one of


the following cases
switch (monthnumber)
{
case 1: monthname = "Jan"; break;
case 2: monthname = "Feb"; break;
case 3: monthname = "Mar"; break;
case 4: monthname = "Apr"; break;
case 5: monthname = "May"; break;
case 6: monthname = "Jun"; break;
case 7: monthname = "Jul"; break;
case 8: monthname = "Aug"; break;
case 9: monthname = "Sep"; break;
case 10: monthname = "Oct"; break;
case 11: monthname = "Nov"; break;
case 12: monthname = "Dec"; break;
default: monthname = "unknown"; break;
}
System.Console.WriteLine(monthname); //Output: Jul
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 108 | 1583


C#.NET 8.0

Output

While
while

Sl. Control Syntax Description


No Statement

1 While while (condition) It executes the code repeatedly, while the


{ condition is TRUE.
your code here
If exits from the loop automatically when the
}
condition is FALSE.

While - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “WhileExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “WhileExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 109 | 1583


C#.NET 8.0

Program.cs
class Program
{
static void Main()
{
//initialization
int i = 1;
//condition
while (i <= 10)
{
System.Console.WriteLine(i);
i++; //incrementation
}
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 110 | 1583


C#.NET 8.0

Do – While
do-while

Sl. Control Syntax Description


No Statement

1 Do-While do It repeats the code execution while the


{ condition is TRUE.
Your code here
It executes the code at least once. That means
} while( condition );
it will not check the condition for the first
iteration.

If exit from the loop automatically when the


condition is FALSE.

Do – While - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “DoWhileExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DoWhileExample”.

• Click on OK.

Program.cs
class Program
{

D. Harsha Vardhan (.NET Expert) P a g e 111 | 1583


C#.NET 8.0

static void Main()


{
//initialization
int i = 1;
do
{
System.Console.WriteLine(i);
i++; //incrementation
} while (i <= 10); //condition
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 112 | 1583


C#.NET 8.0

for
for

Sl. Control Syntax Description


No Statement

1 for for (initialization ; condition ; iteration ) Initialization,


{ condition, iteration
Your code here (increment or
} decrement) are
written in a single line;
so that it is easy to
understand.

for - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ForExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ForExample”.

• Click on OK.

Program.cs
class Program
{

D. Harsha Vardhan (.NET Expert) P a g e 113 | 1583


C#.NET 8.0

static void Main()


{
//initialization; condition; incrementation
for (int i = 1; i <= 10; i++)
{
System.Console.WriteLine(i);
}
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 114 | 1583


C#.NET 8.0

Break

Sl. Control Syntax Description


No Statement

1 Break break; It terminates (stops) the loop.

Break - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “BreakExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “BreakExample”. Click on OK.

Program.cs
class Program
{
static void Main()
{
//initialization; condition; incrementation
for (int i = 1; i <= 10; i++)
{
System.Console.WriteLine(i);
if (i == 6)
break; //stop the loop when "i" value is reached to "6".

D. Harsha Vardhan (.NET Expert) P a g e 115 | 1583


C#.NET 8.0

}
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Continue
continue

Sl. Control Syntax Description


No Statement

1 Continue continue; It skips the current iteration and jumps to the next iteration.

D. Harsha Vardhan (.NET Expert) P a g e 116 | 1583


C#.NET 8.0

Continue - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ContinueExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ContinueExample”. Click on OK.

Program.cs
class Program
{
static void Main()
{
//initialization; condition; incrementation
for (int i = 1; i <= 10; i++)
{
if (i == 6)
continue; //skip "6" and go to "7"

System.Console.WriteLine(i);
}
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 117 | 1583


C#.NET 8.0

Output

Goto
goto

Sl. Control Syntax Description


No Statement

1 Goto goto LabelName; It jumps to the specified label, within the same
method.

Goto - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “GotoExample”.

• Type the location as “C:\CSharp”.

D. Harsha Vardhan (.NET Expert) P a g e 118 | 1583


C#.NET 8.0

• Type the solution name as “GotoExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
System.Console.WriteLine("one");
System.Console.WriteLine("two");

//jump to mylabel
goto mylabel;

System.Console.WriteLine("three");
System.Console.WriteLine("four");
System.Console.WriteLine("five");

//mylabel starts here


mylabel:
System.Console.WriteLine("six");
System.Console.WriteLine("seven");

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 119 | 1583


C#.NET 8.0

Output

Nested For Loops


Syntax of Nested For Loop Description
for (initialization ; condition ; iteration ) The “inner for loop” executes ‘n’ no. of
{ times, while the condition outer for
for (initialization ; condition ; iteration )
loop’s condition is true.
{
Your code here
}
}

Nested For Loops - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “NestedForLoopsExample”.

D. Harsha Vardhan (.NET Expert) P a g e 120 | 1583


C#.NET 8.0

• Type the location as “C:\CSharp”.

• Type the solution name as “NestedForLoopsExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//outer loop (5 times)
for (int i = 1; i <= 5; i++)
{
//inner loop (10 times)
for (int j = 1; j <= 10; j++)
{
System.Console.Write(j);
System.Console.Write(", ");
}
System.Console.WriteLine();
}
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 121 | 1583


C#.NET 8.0

Output

D. Harsha Vardhan (.NET Expert) P a g e 122 | 1583


C#.NET 8.0

C#.NET – Object Oriented


Programming (OOP)

Introduction to Object Oriented Programming

Types of Programming Languages

1. Imperative Programming Languages:

o The programs are written as a series of statements that execute in top-to-bottom


approach.

o Ex: BASIC, Assembly languages

2. Structured Programming Languages:

o These are also imperative programming languages with control structures like if,
switch-case, while, do-while, for, break, continue, return etc.

o Ex: Cobol, Pascal

3. Procedural Programming Languages:

o These are also structured programming languages with procedures (functions)


concept.

o A procedure or function is a collection statements present independently in the


program and can be called many times during the normal flow of execution.

o Ex: C

4. Object Oriented Programming Languages:

o These are also procedural programming languages with objects and classes.

o Object is a physical item; Class is a model of object.

o Ex: C++, Java, C#.NET

D. Harsha Vardhan (.NET Expert) P a g e 123 | 1583


C#.NET 8.0

Introduction of Object Oriented Programming (OOP)

• “Object oriented programming” is a programming style / programming paradigm, which


provides necessary guidelines for the programmers to write the programs in a well-
organized, understandable, secured, re-usable, efficient, structured, clean, maintainable
manner.

• OOP is followed in almost-all modern programming languages such as C++, VC++, Java,
C#.NET, VB.NET etc.

• .NET developers must know OOP.

• Advantages of OOP:

1. Modularity: Dividing large programs into multiple parts called classes.

2. Re-usability: The class created once can be called many times.

3. Security: The members of a class can be private or public. The private members
can’t be accessible outside the class.

Object

• An object represents a real world item. For example, you are an object, your laptop is an
object, and your city is an object.

• An object consists of "details" and "functionality".

• Details are called as "fields".

• Functionality is called as "functions" or "methods" or "operations".

• All the objects will be stored in an area called "heap" in RAM.

D. Harsha Vardhan (.NET Expert) P a g e 124 | 1583


C#.NET 8.0

Fields

• Fields also called as "details".

• The variables inside object are called as "Fields".

• Fields are used to store data.

Methods

• Methods also called as "functionality" or "functions" or "operations".

• A method is a "set of statements" to do a particular task in the program.

• Methods are used to manipulate Fields.

Example:

D. Harsha Vardhan (.NET Expert) P a g e 125 | 1583


C#.NET 8.0

Class

• A class is a "model" or “type” or "blue-print" of object.

• Class is used to define the common members of similar objects.

 For example, there are 10 students. Each student is an object. So 10 students are
10 objects. In each student, we want to store "studentid", "studentname", "marks".
So first we have to create a class called "Student" and we have to create
"studentid", "studentname", "marks" as members of the "Student" class. Then we
have to create objects based on the class.

• A class specifies the list of Fields and methods that you want to store in every object.

• For a class, memory will not be allocated.

• So you must create an object for the class, in order to access its members.

• Class is a just “model” only; no actual data will be stored in class. Object is the “real
instance”; actual data will be stored in object only.

• Based on a class, any no. of objects can be created.

• When an object is created, the following process happens.

1. Memory will be allocated in RAM (Random Access Memory) for the object.

2. All the Fields of the class will be stored in the object.

3. Fields of the object will be initialized with default values.

▪ Numerical Fields: 0

▪ Char / string: null

▪ Bool: false

▪ DateTime: 1/1/0001 12:00:00 AM

4. Constructor will be called. Constructors will be explained later in this book.

• All the objects are stored in RAM (temporarily). Objects are created when the program
execution starts. Objects are automatically deleted (erased from memory) when the
program execution ends.

D. Harsha Vardhan (.NET Expert) P a g e 126 | 1583


C#.NET 8.0

• Each object’s memory will be allocated separately in RAM.

Example:

D. Harsha Vardhan (.NET Expert) P a g e 127 | 1583


C#.NET 8.0

Reference variables

• A “reference variable” stores address of an object of same class.

• You should store the “address of an object” in the reference variable; through the
reference variable only, we can access the object, in further statements.

• All reference variables will be stored in an area called "stack" in RAM.

Syntax of creating class

class Classname
{
Class members here
}

Syntax of creating a Field in a class:

accessmodifier qualifier datatype Fieldname = value;

Syntax of creating a method in a class:

accessmodifier qualifier returntype methodname(arguments)


{
Code here
}

D. Harsha Vardhan (.NET Expert) P a g e 128 | 1583


C#.NET 8.0

Syntax of creating reference variable

Classname Referencevariablename ;

Syntax of creating object (in heap):

new Classname ( );

Memory allocation of Objects

• All the reference variables are stored in an area called "stack" in RAM. For every method
call, a “stack” will be created automatically.

• All the objects are stored in an area called "heap" in RAM. For entire application, a “heap”
will be created.

• You must store the address of an object into the reference variable; otherwise you can't
access the object.

D. Harsha Vardhan (.NET Expert) P a g e 129 | 1583


C#.NET 8.0

Principles of Object Oriented Programming

Principles of OOP

• OOP following the following principles.

1) Encapsulation

2) Abstraction

3) Inheritance

4) Polymorphism

Encapsulation:

• Encapsulation is a concept of combining Fields and methods as a single unit called


“object”.

• This is implemented by creating classes with Fields and methods.

• Fields are variables that stores the data; Methods are functions that manipulates
the data.

Abstraction:

• Abstraction is a concept of hiding implementation details (internal logic) and


providing only necessary details to other classes.

• This is implemented by creating private Fields and public methods.

Inheritance:

• Inheritance is a concept of creating “parent-child” relationship among two or more


classes.

D. Harsha Vardhan (.NET Expert) P a g e 130 | 1583


C#.NET 8.0

• As a result of inheritance, all the members of parent class are accessible in child
class.

Polymorphism:

• Polymorphism means "decision making".

• Polymorphism means “the ability of a statement that calls different methods at


different situations”.

Types of polymorphism:

A. Static polymorphism (or) Compile-time polymorphism (or) Early binding:

▪ Static polymorphism means method overloading.

▪ Method overloading is a concept of creating multiple methods with same


name in the same class with different types of arguments. While calling
the method, the matching method will be executed, depending on the
arguments that are passed.

▪ The decision of which method is to be executed will be taken at


compilation time (by c#.net compiler). That’s why it is called “Compile-
time polymorphism”.

▪ Example of static polymorphism: Method overloading

B. Dynamic polymorphism (or) Run-time polymorphism (or) Late binding:

▪ Dynamic polymorphism means method overriding.

▪ Method overriding is a concept of creating two methods with same name


and same signature; one is in parent class and other one is in child class;
both methods have different code.

D. Harsha Vardhan (.NET Expert) P a g e 131 | 1583


C#.NET 8.0

▪ You will create a reference variable for the parent class (or) interface;
assign the reference of child class’s object; and call the method. Then the
current child class’s method will be called.

▪ The decision of which class’s method is to be executed will be taken at run


time (by .net CLR). That’s why it is called “Run-time polymorphism”.

▪ Example of dynamic polymorphism: Reference variable of interface type.

Access Modifiers

Access Modifiers

• Access Modifiers are also called as “Access Specifiers”, which are used to specify the access
privileges of a member of a class.

• Access Modifiers can be applicable to all types of members (such as Field, method,
constructor, property etc.) that tell which classes can access the member and which can’t.

• Access Modifiers are used to create security for the member of a class.

• List of access modifiers in c#.net:

1. private (default)

2. protected

3. internal

4. protected internal

5. public

D. Harsha Vardhan (.NET Expert) P a g e 132 | 1583


C#.NET 8.0

1. private: The private members are accessible “only within the same class”. These are
not accessible in any other classes. “Private” is the default access modifier in c#.net.
That means, if you don’t specify any access modifier, by default, “private” will be
applied.

2. protected: The protected members are accessible “within the same class” and also
within the “child classes at same project” and “child classes at other projects”. These
are not accessible in any other classes. Note: The other projects must add the
reference of current project.

3. internal: The internal members are accessible “anywhere within the same project”.
These are not accessible in any classes at other projects.

4. protected internal: “Protected internal” is a combination of “protected” and “internal”.


The protected internal members are accessible “anywhere within the project” and also
accessible “within the child classes at other projects”. These are not accessible in other
classes at other projects. Note: The other projects must add the reference of current
project.

5. public: The public members are accessible “everywhere”.

D. Harsha Vardhan (.NET Expert) P a g e 133 | 1583


C#.NET 8.0

D. Harsha Vardhan (.NET Expert) P a g e 134 | 1583


C#.NET 8.0

Access Modifiers - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “AccessModifiersExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “AccessModifiersExample”. Click on OK.

Program.cs
namespace AccessModifiersExample
{
//same class
class Class1
{
private int a; //private member
protected int b; //protected member
internal int c; //internal member
protected internal int d; //protected internal member
public int e; //public member

public void Method1()


{
a = 10; //private member is accessible in the same class
b = 20; //protected member is accessible in the same class
c = 30; //internal member is accessible in the same class
d = 40; //protected internal member is accessible in the same class
e = 50; //public member is accessible in the same class
}

D. Harsha Vardhan (.NET Expert) P a g e 135 | 1583


C#.NET 8.0

//child class in the same project


class Class2: Class1
{
public void Method2()
{
b = 20; //protected member is accessible in the child class at same
project
c = 30; //internal member is accessible in the child class at same
project
d = 40; //protected internal member is accessible in the child class at
same project
e = 50; //public member is accessible in the child class at same project
}
}

//other class in the same project


class Class3
{
public void Method3()
{
Class1 c1 = new Class1();
c1.c = 30; //internal member is accessible in the other class at same
project
c1.d = 40; //protected internal member is accessible in the other class
at same project
c1.e = 50; //public member is accessible in the other class at same
project
}
}

//other class in the same project


class Program
{
static void Main()
{

D. Harsha Vardhan (.NET Expert) P a g e 136 | 1583


C#.NET 8.0

Class1 c1 = new Class1();


c1.c = 30; //internal member is accessible in the other class at same
project
c1.d = 40; //protected internal member is accessible in the other class
at same project
c1.e = 50; //public member is accessible in the other class at same
project

System.Console.WriteLine("Done");
System.Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 137 | 1583


C#.NET 8.0

Access Modifiers for classes

Access Modifiers for Classes

• Access Modifiers can be used for classes also, to specify where the class is accessible.

• The following access modifiers can be used for classes:

• List of access modifiers for classes in c#.net:

1. internal (default)

2. public

3. private

1. internal: The internal classes can be accessible within the same project only. They are
not accessible in other projects. “Internal” is the default access modifier for the classes.

2. public: The public classes can be accessible anywhere (within the same project and also
in other projects too).

3. private: Only inner classes can be “private classes”. The “private inner classes” can be
accessible within the same outer classes only. They are not accessible in other classes.

Object Oriented Programming – Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 138 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “OOPExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “OOPExample”.

• Click on OK.

Program.cs
class Sample
{
public int a, b;
}

class Program
{
static void Main()
{
Sample s1; //create reference variable
s1 = new Sample(); //create object
s1.a = 10;
s1.b = 20;

Sample s2; //create reference variable


s2 = new Sample(); //create object
s2.a = 30;
s2.b = 40;

//display values
System.Console.WriteLine(s1.a); //Output: 10
System.Console.WriteLine(s1.b); //Output: 20
System.Console.WriteLine(s2.a); //Output: 30
System.Console.WriteLine(s2.a); //Output: 40

System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 139 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Object Oriented Programming – Student Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “OOPStudentExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “OOPStudentExample”.

• Click on OK.

Program.cs
class Student
{
public int StudentId;
public string StudentName;
public int Marks;

D. Harsha Vardhan (.NET Expert) P a g e 140 | 1583


C#.NET 8.0

class Program
{
static void Main()
{
//create reference variables
Student s1, s2;

//create objects
s1 = new Student();
s2 = new Student();

//set data into first object


System.Console.Write("Enter first student id: ");
s1.StudentId = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student name: ");
s1.StudentName = System.Console.ReadLine();
System.Console.Write("Enter first student marks: ");
s1.Marks = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();

//set data into second object


System.Console.Write("Enter second student id: ");
s2.StudentId = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter second student name: ");
s2.StudentName = System.Console.ReadLine();
System.Console.Write("Enter second student marks: ");
s2.Marks = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();

//get data from first object


System.Console.WriteLine("Student ID: " + s1.StudentId);
System.Console.WriteLine("Student Name: " + s1.StudentName);
System.Console.WriteLine("Marks: " + s1.Marks);
System.Console.WriteLine("---------------------------------------");

//get data from second object


System.Console.WriteLine("Student ID: " + s2.StudentId);
System.Console.WriteLine("Student Name: " + s2.StudentName);
System.Console.WriteLine("Marks: " + s2.Marks);
System.Console.WriteLine("---------------------------------------");

System.Console.ReadKey();

D. Harsha Vardhan (.NET Expert) P a g e 141 | 1583


C#.NET 8.0

}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Object Oriented Programming – Employee Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “OOPEmployeeExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “OOPEmployeeExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 142 | 1583


C#.NET 8.0

Program.cs

class Employee
{
public int EmployeeId;
public string EmployeeName;
public int Salary;
}

class Program
{
static void Main()
{
//create reference variables
Employee s1, s2;

//create objects
s1 = new Employee();
s2 = new Employee();

//set data into first object


System.Console.Write("Enter first Employee id: ");
s1.EmployeeId = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first Employee name: ");
s1.EmployeeName = System.Console.ReadLine();
System.Console.Write("Enter first Employee Salary: ");
s1.Salary = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();

//set data into second object


System.Console.Write("Enter second Employee id: ");
s2.EmployeeId = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter second Employee name: ");
s2.EmployeeName = System.Console.ReadLine();
System.Console.Write("Enter second Employee Salary: ");
s2.Salary = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();

//get data from first object


System.Console.WriteLine("Employee ID: " + s1.EmployeeId);
System.Console.WriteLine("Employee Name: " + s1.EmployeeName);

D. Harsha Vardhan (.NET Expert) P a g e 143 | 1583


C#.NET 8.0

System.Console.WriteLine("Salary: " + s1.Salary);


System.Console.WriteLine("---------------------------------------");

//get data from second object


System.Console.WriteLine("Employee ID: " + s2.EmployeeId);
System.Console.WriteLine("Employee Name: " + s2.EmployeeName);
System.Console.WriteLine("Salary: " + s2.Salary);
System.Console.WriteLine("---------------------------------------");

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 144 | 1583


C#.NET 8.0

Static Fields
• Static Fields are used to common data that belongs to all the objects. Non-Static Fields are
stored in the objects; Static Fields are stored outside the objects. Static members are not
accessible with reference variable, but accessible with “class name”.

• Fields are two types:


1. Non-static Fields (or) Instance Fields
2. Static Fields (or) Shared Fields

Sl. Non-Static Fields Static Fields


No

1 By default, all the Fields are non-static Fields. Static Fields are created using “static” keyword.
These are not created with a keyword called
“static”.

2 Non static Fields are stored in the object. That For static Fields, memory will not be allocated in
means when you create an object for the class, the object. When you access the class name for
the memory will be allocated for all the non- the first time in the main method, then memory
static Fields in the object. will be allocated for the static Fields.

3 Non-static Field’s memory will be allocated Static Field’s memory will be allocated only once
separately for every object of the class. for entire project.

4 Non-static Fields accessible with reference Static Fields are accessible with class.
variable.

5 If you don’t create an object for the class, no If you don’t access the class in the entire
memory will be allocated for non-static Field. program, no memory will be allocated for static
Fields.

6 Use non-static Fields if you want to store Use static Fields if you want to store common
object-specific data (which is different for data that belongs to all the objects.
each object).

D. Harsha Vardhan (.NET Expert) P a g e 145 | 1583


C#.NET 8.0

Static Fields - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “StaticFieldsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “StaticFieldsExample”.

• Click on OK.

Program.cs
using System;

namespace StaticFieldsExample
{
//creating a class called "Student".
class Student
{
//instance Fields (or) non-static Fields
public int studentid;
public string studentname;
public int marks;

//static Field (or) shared Field


public static string collegename;
}

class Program
{

D. Harsha Vardhan (.NET Expert) P a g e 146 | 1583


C#.NET 8.0

static void Main()


{
//create two reference variables
Student s1;
Student s2;

//create two objects


s1 = new Student();
s2 = new Student();

//set data into members of s1


s1.studentid = 1;
s1.studentname = "scott";
s1.marks = 70;

//set data into members of s2


s2.studentid = 2;
s2.studentname = "allen";
s2.marks = 80;

//get data from members of s1


Console.WriteLine("Student ID: " + s1.studentid);
Console.WriteLine("Student Name: " + s1.studentname);
Console.WriteLine("Marks: " + s1.marks);
Console.WriteLine();

//get data from members of s2


Console.WriteLine("Student ID: " + s2.studentid);
Console.WriteLine("Student Name: " + s2.studentname);
Console.WriteLine("Marks: " + s2.marks);
Console.WriteLine();

//set data into static Field


Student.collegename = "ABC college of technology";

//get data from static Field


Console.WriteLine("College Name: " + Student.collegename);

D. Harsha Vardhan (.NET Expert) P a g e 147 | 1583


C#.NET 8.0

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 148 | 1583


C#.NET 8.0

Constant Fields

Constant Fields
• Constant Field’s value can’t be changed in the rest life of the object.

• Constant Fields must be initialized along with the declaration. Those can’t be initialized in
the constructor.

• Constant Fields are created using “const” keyword.

• Constant Fields are by default “static”; so they are accessible without creating an object for
the class, using class name.

• Syntax:

Accessmodifier const Datatype Constantname = value;

Constant Fields - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ConstantsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ConstantsExample”. Click on OK.

Program.cs
class Sample

D. Harsha Vardhan (.NET Expert) P a g e 149 | 1583


C#.NET 8.0

{
public const int NoOfMonthsInYear = 12;
}

class Program
{
static void Main()
{
System.Console.WriteLine(Sample.NoOfMonthsInYear);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 150 | 1583


C#.NET 8.0

ReadOnly Fields

Read-only Fields
• Read-only Fields must be initialized along with the declaration or in the constructor. It
must be initialized before constructor ends.

• Read-only Field’s value can’t be changed in the rest life of the object.

• Read-only Fields are created using “readonly” keyword.

• Syntax:

Accessmodifier readonly Datatype Fieldname = Value;

Constant Fields (vs) Readonly Fields

Sl. No Constant Field Readonly Field

1 Declared with "const" keyword. Declared with "readonly" keyword.

2 Can be created in a method or as a Can be created as a Field only.


Field.

3 Should be initialized along with its Should be initialized either along with its
declaration. declaration or in the constructor.

4 Useful to initialize a fixed value only. Useful to initialize fixed value or result of a
calculation.

ReadOnly Fields - Example

Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ReadOnlyExample”.

• Type the location as “C:\CSharp”.

D. Harsha Vardhan (.NET Expert) P a g e 151 | 1583


C#.NET 8.0

• Type the solution name as “ReadOnlyExample”. Click on OK.

Program.cs
class Sample
{
public readonly int NoOfMonthsInYear = 12;
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
System.Console.WriteLine(s.NoOfMonthsInYear);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 152 | 1583


C#.NET 8.0

Methods

Methods
▪ The method is a “function” inside the class.

▪ The method is a set of instructions (statements) to perform a particular task.

▪ The method is a “re-usable code block”.

▪ Methods are used to divide the large code as small units.

▪ Methods improve the understandability of the program.

▪ Every method should have a name.

▪ Methods can be called any no. of times.

▪ Methods can be created and called in any order.

▪ Arguments: The value that are passed from calling portion to the method definition are
called arguments or parameters. The data type of argument is called “argument type”.
Every argument can be different type.

▪ Return Value: The value that is passed from method definition to the calling portion is
called “return value”. A method can return only one value maximum. The data type of
return value is called “return type”. If a method doesn’t return any value, its return type
should be said as “void”.

Syntax of creating a method


AccessModifier Qualifier ReturnType Methodname (DataType1
ArgumentVariable1, DataType2 ArgumentVariable2, …)
{
Your code here
return (value );
}

D. Harsha Vardhan (.NET Expert) P a g e 153 | 1583


C#.NET 8.0

Methods – Simple Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MethodsSimpleExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MethodsSimpleExample”.

• Click on OK.

Program.cs
class Sample
{
public void Address()
{
System.Console.WriteLine("Ameerpet");
System.Console.WriteLine("Hyderabad");
System.Console.WriteLine("India");
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
s.Address();
s.Address();
s.Address();
System.Console.ReadKey();
}

D. Harsha Vardhan (.NET Expert) P a g e 154 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Methods – Arguments and Return Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ArgumentsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ArgumentsExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 155 | 1583


C#.NET 8.0

Program.cs
class Sample
{
public int Add(int a, int b)
{
int c;
c = a + b;
return (c);
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
System.Console.WriteLine(s.Add(10, 20));
System.Console.WriteLine(s.Add(50, 30));
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 156 | 1583


C#.NET 8.0

Scope of Variables

Scopes of Variables
▪ “Life time” of the variable is called as “scope”.

▪ C#.NET supports three scopes:

1. Local variables:

▪ Declared inside a method.

▪ Accessible within the same method only.

2. Block level variables:

▪ Declared inside a block. Ex: if block, for block etc.

▪ Accessible within the same block only.

3. Class level variables / Fields:

▪ Declared inside a class.

▪ Accessible within all the methods of same class.

D. Harsha Vardhan (.NET Expert) P a g e 157 | 1583


C#.NET 8.0

Methods – Example - Age

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MethodsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MethodsExample”.

• Click on OK.

Program.cs
class Person
{
public int age = 20;

public void Birthday()


{
age++;
}
}

class Program

D. Harsha Vardhan (.NET Expert) P a g e 158 | 1583


C#.NET 8.0

{
static void Main()
{
Person p;
p = new Person();
System.Console.WriteLine(p.age);
p.Birthday();
System.Console.WriteLine(p.age);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 159 | 1583


C#.NET 8.0

Methods – Example 2 - Numbers

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MethodsExample2”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MethodsExample2”.

• Click on OK.

Program.cs
class Class1
{
public double a, b;
public double sum;

D. Harsha Vardhan (.NET Expert) P a g e 160 | 1583


C#.NET 8.0

public double difference;


public double product;
public double quotient;

public void Add()


{
sum = a + b;
}
public void Subtract()
{
difference = a - b;
}
public void Multiply()
{
product = a * b;
}
public void Divide()
{
quotient = a / b;
}
}

class Program
{
static void Main()
{
Class1 c1;
c1 = new Class1();
System.Console.Write("Enter first number : ");
c1.a = System.Convert.ToDouble(System.Console.ReadLine());
System.Console.Write("Enter second number : ");
c1.b = System.Convert.ToDouble(System.Console.ReadLine());
c1.Add();
System.Console.WriteLine("Sum: " + c1.sum);
c1.Subtract();
System.Console.WriteLine("Difference: " + c1.difference);
c1.Multiply();
System.Console.WriteLine("Product: " + c1.product);
c1.Divide();
System.Console.WriteLine("Quotient: " + c1.quotient);
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 161 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 162 | 1583


C#.NET 8.0

Methods – Example 3 - Login

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “LoginExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “LoginExample”. Click on OK.

Program.cs
class User
{
public string Username;
public string Password;
public string Message;
public void CheckLogin()
{
if (Username == "admin" && Password == "manager")
{
Message = "Successful login";

D. Harsha Vardhan (.NET Expert) P a g e 163 | 1583


C#.NET 8.0

}
else
{
Message = "Invalid login";
}
}
}

class Program
{
static void Main()
{
User u;
u = new User();
System.Console.Write("Enter username : ");
u.Username = System.Console.ReadLine();
System.Console.Write("Enter password : ");
u.Password = System.Console.ReadLine();
u.CheckLogin();
System.Console.WriteLine(u.Message);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 164 | 1583


C#.NET 8.0

Methods – Example 4 - Student

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “StudentExample”.

D. Harsha Vardhan (.NET Expert) P a g e 165 | 1583


C#.NET 8.0

• Type the location as “C:\CSharp”.

• Type the solution name as “StudentExample”.

• Click on OK.

Program.cs
class Student
{
public int studentid;
public string studentname;
public double marks1, marks2, marks3, totalmarks, averagemarks;
public string grade;
public void calculatetotalmarks()
{
totalmarks = marks1 + marks2 + marks3;
}
public void calculateaveragemarks()
{
averagemarks = totalmarks / 3;
}
public void calculategrade()
{
if (marks1 < 35 || marks2 < 35 || marks3 < 35)
{
grade = "Fail";
}
else if (averagemarks >= 80 && averagemarks <= 100)
{
grade = "A grade";
}
else if (averagemarks >= 60 && averagemarks < 79)
{
grade = "B grade";
}
else if (averagemarks >= 50 && averagemarks < 59)
{
grade = "C grade";
}
else if (averagemarks >= 35 && averagemarks < 49)
{
grade = "D grade";

D. Harsha Vardhan (.NET Expert) P a g e 166 | 1583


C#.NET 8.0

}
}
}

class Program
{
static void Main()
{
Student s1, s2;
s1 = new Student();
s2 = new Student();
System.Console.Write("Enter first student id: ");
s1.studentid = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student name: ");
s1.studentname = System.Console.ReadLine();
System.Console.Write("Enter first student marks 1: ");
s1.marks1 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student marks 2: ");
s1.marks2 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student marks 3: ");
s1.marks3 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();

System.Console.Write("Enter second student id: ");


s2.studentid = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter second student name: ");
s2.studentname = System.Console.ReadLine();
System.Console.Write("Enter second student marks 1: ");
s2.marks1 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter second student marks 2: ");
s2.marks2 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter second student marks 3: ");
s2.marks3 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();

s1.calculatetotalmarks();
s1.calculateaveragemarks();
s1.calculategrade();

s2.calculatetotalmarks();
s2.calculateaveragemarks();
s2.calculategrade();

System.Console.WriteLine("First Student ID: " + s1.studentid);

D. Harsha Vardhan (.NET Expert) P a g e 167 | 1583


C#.NET 8.0

System.Console.WriteLine("First Student Name: " + s1.studentname);


System.Console.WriteLine("First Student Marks 1: " + s1.marks1);
System.Console.WriteLine("First Student Marks 2: " + s1.marks2);
System.Console.WriteLine("First Student Marks 3: " + s1.marks3);
System.Console.WriteLine("First Student Total Marks: " +
s1.totalmarks);
System.Console.WriteLine("First Student Average Marks: " +
s1.averagemarks);
System.Console.WriteLine("First Student Grade: " + s1.grade);
System.Console.WriteLine("--------------------------------------");

System.Console.WriteLine("Second Student ID: " + s2.studentid);


System.Console.WriteLine("Second Student Name: " +
s2.studentname);
System.Console.WriteLine("Second Student Marks 1: " + s2.marks1);
System.Console.WriteLine("Second Student Marks 2: " + s2.marks2);
System.Console.WriteLine("Second Student Marks 3: " + s2.marks3);
System.Console.WriteLine("Second Student Total Marks: " +
s2.totalmarks);
System.Console.WriteLine("Second Student Average Marks: " +
s2.averagemarks);
System.Console.WriteLine("Second Student Grade: " + s2.grade);
System.Console.WriteLine("--------------------------------------");

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 168 | 1583


C#.NET 8.0

Output

D. Harsha Vardhan (.NET Expert) P a g e 169 | 1583


C#.NET 8.0

"this" keyword

this keyword
• “this” is a keyword, which represents “current object”, based on which, the method or
constructor was called.

• “this” keyword can be used in non-static methods and non-static constructors only. “this”
keyword can’t be used in static methods or static constructors.

• It is used to access the members of current object.

• By default, the usage of “this” keyword is optional. By default system referrers to “current
object”. But when a local variable name and Field name are same, then by default the
system refers to local variable. Then if you want to access Field name, you must use
“this.Field”. So in that way “this” keyword is must to use.

"this" keyword - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ThisExample”.

• Type the location as “C:\CSharp”.

D. Harsha Vardhan (.NET Expert) P a g e 170 | 1583


C#.NET 8.0

• Type the solution name as “ThisExample”.

• Click on OK.

Program.cs
class Class1
{
public int n = 10;
public void Display()
{
int n = 20;
System.Console.WriteLine("data member: " + this.n); //Output: 20
System.Console.WriteLine("local variable: " + n); //Output: 20
System.Console.WriteLine();
}
}

class Program
{
static void Main()
{
Class1 c1;
c1 = new Class1();
c1.Display();
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 171 | 1583


C#.NET 8.0

Static Methods

Static Methods
• Non-static methods are used to manipulate non-static Fields; Static methods are used to
manipulate static Fields only. Static methods can be called with class name only.

• Methods are two types:

1. Non-static methods (or) instance methods

2. Static methods (or) shared methods

Sl. Non-Static Methods Static Methods


No

1 By default, all the methods are non- Static methods are created using “static”
static methods. These are not created keyword.
with a keyword called “static”.

2 Non-static methods can access both Static methods can access only static members.
non-static members and non-static Static methods can’t access non-static members.
members. However, if you create an object for the class in
the static methods, then you can access any non-
static members though the object, in the static
method.

3 Non-static methods are accessible with Static methods are accessible with class only.
object only. Non-static methods are not Static methods are accessible without creating an
accessible without creating an object object for the class. Static methods are not
for the class. accessible with an object.

4 We can use “this” keyword in the non- We can’t use “this” keyword in the static
static methods, because non-static methods, because static methods are called with
methods are called with an object. class only, without an object.

5 Use non-static methods, if you want to Use static Fields if you want to perform some
perform some operation based on non- operation based on static Fields.
static Fields.

D. Harsha Vardhan (.NET Expert) P a g e 172 | 1583


C#.NET 8.0

Static Methods - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”. Select “Console Application”.

• Type the project name as “StaticMethodsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “StaticMethodsExample”.

• Click on OK.

Program.cs
class Sample
{
public static int n = 10;
public static void Increment()
{
n++;
}
}

class Program
{
static void Main()
{
System.Console.WriteLine(Sample.n); //Output: 10
Sample.Increment();
System.Console.WriteLine(Sample.n); //Output: 11
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 173 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 174 | 1583


C#.NET 8.0

Reference Variables as Arguments

Reference Variables as Arguments


• We can pass objects as arguments from one method to another method. Then the
reference (address) of the source object will be sent to the argument variable.

Reference Variables as Arguments - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ReferenceVariablesAsArguments”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ReferenceVariablesAsArguments”.

• Click on OK.

Program.cs
class Person
{
public int age;
}

class Sample
{
public void Birthday(Person p)
{
p.age++;
}

D. Harsha Vardhan (.NET Expert) P a g e 175 | 1583


C#.NET 8.0

class Program
{
static void Main()
{
Person p;
p = new Person();
Sample s;
s = new Sample();
p.age = 20;
s.Birthday(p);
System.Console.WriteLine(p.age);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 176 | 1583


C#.NET 8.0

Reference Variables as Fields

Reference Variables as Fields


• We can create an object of one class (source class) and store its reference in a Field of
another class (destination class).

• If you do so, we can access the source class’s object, through the Field of destination class.
Then the data type of the Field should be “source class” type.

• For example, assume you have a class called “Hyderabad”. You can create an object for
“Hyderabad” class and store its reference in a Field called “h” in another class called “India”.

Reference Variables as Fields - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ReferenceVariablesAsFields”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ReferenceVariablesAsFields”.

• Click on OK.

Program.cs
class Hyderabad
{
public string Charminar = "Hyderabad.Charminar";
public string Golconda = "Hyderabad.Golconda";

D. Harsha Vardhan (.NET Expert) P a g e 177 | 1583


C#.NET 8.0

class India
{
public Hyderabad h = new Hyderabad();
}

class Program
{
static void Main()
{
India i;
i = new India();
System.Console.WriteLine(i.h.Charminar);
System.Console.WriteLine(i.h.Golconda);
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 178 | 1583


C#.NET 8.0

Default Arguments

Default Arguments (or) Optional Parameters


▪ “Default arguments” concept is used to specify a “default value” for a “argument”.

▪ While calling the method, if you don’t supply a value for the parameter, then the default
value will be assigned to the parameter automatically.

▪ If you supply a value for the parameter, then the given value will be assigned to the
parameter, as usual.

Syntax of method with Default Arguments


AccessModifier Qualifier MethodName (DataType1 ArgumentVariable1 =
DefaultValue1, DataType2 ArgumentVariable2 = DefaultValue2, …)
{
Your Code here
}

Default Arguments - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”. Select “Console Application”.

• Type the project name as “DefaultArgumentsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DefaultArgumentsExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 179 | 1583


C#.NET 8.0

Program.cs
class Sample
{
public void Display(int n = 10)
{
System.Console.WriteLine("n value is " + n);
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
s.Display(50); //Output: 50
s.Display(100); //Output: 100
s.Display(); //Output: 10
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 180 | 1583


C#.NET 8.0

Named Parameters
▪ “Named parameters” concept allows the programmer to pass a value, based on the
“parameter name”, instead of depending on the order of arguments, while calling a method.

▪ Advantage: We can change the order of parameters.

▪ Syntax:

MethodName(ParameterName : value, ParameterName : value, …)

Named Parameters - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “NamedParametersExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “NamedParametersExample”.

• Click on OK.

Program.cs
class Sample
{
public void Display(int x, int y)
{

D. Harsha Vardhan (.NET Expert) P a g e 181 | 1583


C#.NET 8.0

System.Console.WriteLine("x is: " + x);


System.Console.WriteLine("y is: " + y);
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
s.Display(y: 10, x: 20); //Output: x is 20, y is 10
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 182 | 1583


C#.NET 8.0

Methods Overloading
▪ “Method Overloading” concept is “writing multiple methods with same name within the
same class, with different types of arguments”.

▪ The difference can be in data types of arguments or in no. of arguments.

▪ When you call a method, it calls the method, which matches with the given arguments.

▪ Example:

⬧ Method1()
⬧ Method1(int a)
⬧ Method1(double d)
⬧ Method1(int a, double d)
⬧ Method1(double d, int a)
⬧ Method1(string s)
etc.

Methods Overloading - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MethodOverloadingExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MethodOverloadingExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 183 | 1583


C#.NET 8.0

Program.cs
class Sample
{
//method 1
public void Display(int n)
{
System.Console.WriteLine("int: " + n);
}

//method 2
public void Display(string s)
{
System.Console.WriteLine("string: " + s);
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a = 100;
string b = "hello";
s.Display(a); //calls method1
s.Display(b); //calls method2
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 184 | 1583


C#.NET 8.0

Types of Parameters

Types of Parameters
1. Call by value

2. Call by reference

3. Call by output

Call by Value
▪ The changes made to the “argument variable” will not be effected in “original variable”.

▪ This is default in c#.net.

Call by Reference
▪ The changes made to the “argument variable” will be effected automatically in the “original
variable”.

▪ This is implemented using “ref” keyword with “original variable” and “argument variable”.

▪ The “original variable” should be a variable (can’t be a literal).

Call by Output
▪ This is same as “call by reference”.

▪ The difference between “call by reference” and “call by output” is: the value of “original
variable” will not be transferred to the “argument variable”; but the value comes back from
“argument variable” to “original variable”, at the end of method.

▪ The “argument variable” will be “unassigned” by default.

▪ The “argument variable” must be set to a value before the method definition ends.

▪ This is implemented using “out” keyword in both calling portion and receiving portion.

▪ The “original variable” should be a variable; can’t be a literal.

D. Harsha Vardhan (.NET Expert) P a g e 185 | 1583


C#.NET 8.0

Call by value - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”. Select “Console Application”.

• Type the project name as “CallByValueExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “CallByValueExample”.

• Click on OK.

Program.cs
class Sample
{
public void Method1(int x)
{
System.Console.WriteLine(x); //Output: 100
x = 150;
System.Console.WriteLine(x); //Output: 150
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a = 100;
s.Method1(a);
System.Console.WriteLine(a); //Output: 100

D. Harsha Vardhan (.NET Expert) P a g e 186 | 1583


C#.NET 8.0

System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Call by reference - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “CallByReferenceExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “CallByReferenceExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 187 | 1583


C#.NET 8.0

Program.cs
class Sample
{
public void Method1(ref int x)
{
System.Console.WriteLine(x); //Output: 100
x = 150;
System.Console.WriteLine(x); //Output: 150
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a = 100;
s.Method1(ref a);
System.Console.WriteLine(a); //Output: 150
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 188 | 1583


C#.NET 8.0

Call by output - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “CallByOutExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “CallByOutExample”.

• Click on OK.

Program.cs
class Sample
{
public void Method1(out int x)
{
x = 150;
System.Console.WriteLine(x); //Output: 150
}
}

class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a;
s.Method1(out a);
System.Console.WriteLine(a); //Output: 150
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 189 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 190 | 1583


C#.NET 8.0

Type Conversion

Type Conversion in C#.NET


• The process of converting a value from “one data type” to “another data type” is called as
“type conversion”.

• C# supports 4 types of type conversion:

1. Implicit Casting

2. Explicit Casting (or) Type Casting

3. Parsing

4. Conversion Methods

Implicit Casting
• C# compiler automatically converts a value from “lower numeric data type” to “higher
numeric data type”. This automatic conversion is called “implicit casting”.

• We will compare the no. of data types of the data type, to identify whether it is a lower
data type / higher data type.

• Ex: “int” to “long”. Here “int” is 4 bytes and “long” is 8 bytes. So, it is “lower” to “higher”.

• As implicit casting will be performed automatically, there is no syntax for this. Directly you
can assign a value of “lower numeric data type” to “higher numeric data type”.

Implicit Casting - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

D. Harsha Vardhan (.NET Expert) P a g e 191 | 1583


C#.NET 8.0

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ImplicitCastingExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ImplicitCastingExample”. Click on OK.

Program.cs
class Program
{
static void Main()
{
//A variable of "lower numerical data tye" i.e. "short" (2 bytes)
short a = 100;
//A variable of "higher numerical data tye" i.e. "int" (4 bytes)
int b;
//short to int = lower to higher = implicit casting
b = a;
System.Console.WriteLine(a); //Output: 100
System.Console.WriteLine(b); //Output: 100
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 192 | 1583


C#.NET 8.0

Explicit Casting (or) Type Casting


• It is used to convert a value from “lower numerical data type” to “higher numerical data
type” and also from “higher numerical data type” to “lower numerical data type”.

• Syntax: (Expected data type)value

Explicit Casting (or) Type Casting - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “TypeCastingExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “TypeCastingExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variable of "int" data type
int a = 100;
//create variable of "short" data type
short b;

D. Harsha Vardhan (.NET Expert) P a g e 193 | 1583


C#.NET 8.0

//convert the value from "int" data type "short" data type (higher to
lower), using "type casting" concept
b = (short)a;
System.Console.WriteLine(a); //Output: 100
System.Console.WriteLine(b); //Output: 100
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 194 | 1583


C#.NET 8.0

Parsing
▪ It is used to convert a value from “string” data type to “any numerical data type”.

▪ “Parse” is a pre-defined method. Parsing means converting.

▪ Syntax: NumericalDataTypeName.Parse(value);

▪ Rule: The string value should contain digits only; otherwise it can’t be converted into
numerical data type.

▪ Note: If the string value is not convertible into “numerical data type”, you will get exception
(run time error).

Parsing - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ParsingExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ParsingExample”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create variable of "string" data type
string s = "100";

D. Harsha Vardhan (.NET Expert) P a g e 195 | 1583


C#.NET 8.0

//create variable of "int" data type


int x;
//convert the value from "string" to "int" data type, using Parsing
concept
x = int.Parse(s);
System.Console.WriteLine(s); //Output: 100
System.Console.WriteLine(x); //Output: 100
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 196 | 1583


C#.NET 8.0

TryParse
▪ When you are converting "alphabets" or "alpha-numeric value" from "string" data type to
"numeric", you will get a run time error (exception).

▪ "TryParse" is a pre-defined method, which is used to avoid while converting the value from
"string" to "numerical data type".

▪ It tries to convert the string to numerical data type. If conversion is successful, it returns
"true". If conversion is failed, it returns "false". If conversion is successful, it stores the
result value in the destination variable; otherwise, it stores 0 (zero) in the destination
variable.

▪ Syntax: bool result = NumericalDataTypeName.TryParse(source string value, out


destination numerical variable);

TryParse - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “TryParseExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “TryParseExample”.

• Click on OK.

Program.cs
class Program
{

D. Harsha Vardhan (.NET Expert) P a g e 197 | 1583


C#.NET 8.0

static void Main()


{
//create string & integer
string s = "1234";
int n;
//try to convert "1234" into "int" data type. If the conversion is
successful, it returns the value into the "out" parameter & "true" directly. If
the conversion is unsuccessful, it returns "false".
bool b = int.TryParse(s, out n);
//display
System.Console.WriteLine(n); //Output: 1234
System.Console.WriteLine(b); //Output: True
System.Console.ReadKey();
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 198 | 1583


C#.NET 8.0

TryParse – Example 2

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “TryParseExample2”.

• Type the location as “C:\CSharp”.

• Type the solution name as “TryParseExample2”.

• Click on OK.

Program.cs
class Program
{
static void Main()
{
//create string and integer
string s = "hyderabad1234";
int n;

//try to convert "hyderabad1234" into int data type. Actually it not


possible to convert "alphanumeric value" like "hyderabad1234" into "int"
data type. So it returns "0" into "n" and "false" into "b".
bool b = int.TryParse(s, out n);
System.Console.WriteLine(n); //Output: 0
System.Console.WriteLine(b); //Output: False
System.Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 199 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 200 | 1583

You might also like