Harsha Vardhan
Harsha Vardhan
Harsha Vardhan
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
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 Platform” is a software tool, based on which you can develop
applications.
Parts of .NET
3. Xamarin.NET
1. C#.NET
machine.
2. ASP.NET
architecture”.
3. Xamarin.NET
History of .NET
History of .NET
• 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).
Versions of .NET
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
Language)” (also called as “byte code”). The “MSIL code” will be saved in “.exe” file. This
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.
▪ 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”
▪ 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".
▪ 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
▪ 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
machine code; then the user gets the output. So CLR is helps the operating system while
▪ CLR will be installed automatically as a part of “.NET Framework” software. CLR must be
1. Memory Manager: “Memory Manager” is a sub component in CLR, which allocates memory
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
necessary instructions to the operating system, which code should be executed when an
7. Security Manager: “Security Manager” is a sub component in CLR, which takes care about
• 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.
https://www.microsoft.com/en-us/download/details.aspx?id=55167
Windows 8
Windows 8.1
Windows 10
• “.NET Framework Architecture” explains the list of components of .NET Framework, and
Explanation:
• "WinForms", "ASP.NET", and “Other Frameworks” work based on "ADO.NET" and "BCL".
• Finally, the programmers are writing the programs by using the languages called “C#.NET,
“VB.NET” etc.
▪ “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
▪ “CTS” is a set common data types, based on which, the data types of all .net languages
▪ Thus, we achieve the uniform data types among all .net languages.
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
▪ .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
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
• Visual Studio is the “IDE” (Integrated Development Environment), where you can write all
C: drive
Operating System Windows 7 + Service Pack 1 Windows 10
Windows 8.1
Windows 10
Project
• 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
.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.
Solution Folder
Project Folder
o filename.cs
o App.config
o projectname.csproj
o bin\projectname.exe
solutionname.sln
Go to http://www.visualstudio.com
Click on “Run”.
Click on “Continue”.
Check the checkboxes “.NET desktop development” and “ASP.NET and web development”.
Click on “Install”.
Click on “Restart”.
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.
If you click on “Sign up”, you will get the following page.
Click on “Next”.
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.
Now click on “Sign in” in Visual Studio and enter the email.
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 programs run based on the CLR (.NET run time environment).
Versions of C#.NET
Tokens of C#.NET
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,
123$”
• Class names, Interface names, Namespace names, Structure names, Method names,
You must follow the below rules while giving name for identifier.
• Console applications are the programs that run on “Command Prompt” window.
• In console applications, all the input and output will be in the form of characters only.
• Console applications are not used in real time, but good for learning programming basics
• 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”.
• When the program execution starts the “Main” method will be automatically executed.
• The Main method should be “static” method, because it should be called without creating
Syntax:
class classname
{
static void Main()
{
}
}
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
static void Main()
{
System.Console.Write("Hello World");
}
}
Output
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);
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()
• Syntax: System.Console.ReadLine();
• Example: System.Console.ReadLine();
5. System.Console.Clear()
• Syntax: System.Console.Clear();
• Example: System.Console.Clear();
System.Console.WriteLine – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
System.Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
System.Console.ReadKey();
}
}
Output
System.Console.ReadKey – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//display message
System.Console.WriteLine("Hello");
//display message
System.Console.WriteLine("Hello");
//display message
System.Console.WriteLine("Hello");
Output
Press Enter.
Press Enter.
System.Console.Clear - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
Press Enter.
Press Enter.
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 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.
datatype variablename ;
variablename = value ;
variablename
Variables - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
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.
• C# compiler automatically treats a “number without decimal part” as “int” data type, if it is
within the maximum limit of “int” data type.
• 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.
Creating Project
• Open Visual Studio 2019.
• 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;
Output
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
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//get the minimum value of "int" data type
int min = int.MinValue;
Output
char - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
String
String
• String: A string is a group of characters.
• 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.
String - Example
Creating Project
• Open Visual Studio 2019.
Program.cs
class Program
{
static void Main()
{
//create a variable
string s = "Hello 123 $#&";
System.Console.ReadKey();
}
Output
Bool - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
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
4. Relational Operators
5. Logical Operators
6. Concatenation Operator
7. Conditional Operator
Arithmetical Operators
Arithmetical Operators
1 + Addition
2 - Subtraction
3 * Multiplication
4 / Division
5 % Remainder
Creating Project
• Open Visual Studio 2019.
• 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;
//remainder
double g = a % b;
System.Console.ReadKey();
}
}
Output
Assignment Operators
Assignment Operators
1 = Assigns to
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//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();
}
}
Output
1 ++ Increment
2 -- Decrement
Creating Project
• Open Visual Studio 2019.
• 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();
}
}
Output
Relational Operators
Relational Operators
1 == Equal to
2 != Not equal to
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create two variables of "long" data type
long x = 1000, y = 2000;
System.Console.ReadKey();
}
}
Output
Logical Operators
Logical Operators
Creating Project
• Open Visual Studio 2019.
• 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
System.Console.ReadKey();
}
}
Output
Concatenation Operator
Concatenation Operator
• String + String
• String + Number
• Number + String
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create strings
string s1 = "peers";
string s2 = "tech";
string s3;
Output
Conditional Operator
Conditional Operator
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create a variable of "int" data type
int n = -100;
Output
Control Statements
• If
• Switch-case
• While
• Do-While
• For
• Break
• Continue
• Goto
If
If
if (condition)
{
Your code here
}
else
{
Your code here
}
}
else
{
if (condition)
{
Your code here
}
else
{
Your code here
}
}
If - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int n = 100;
Output
If – Else - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int n = 150;
Output
Else – If - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int a = 10, b = 20;
Output
Nested If - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int a = 150, b = 100;
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();
}
}
Output
Switch – Case
Switch-case
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
While
while
While - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//initialization
int i = 1;
//condition
while (i <= 10)
{
System.Console.WriteLine(i);
i++; //incrementation
}
System.Console.ReadKey();
}
}
Output
Do – While
do-while
Do – While - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
for
for
for - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
Break
Break - Example
Creating Project
• Open Visual Studio 2019.
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".
}
System.Console.ReadKey();
}
}
Output
Continue
continue
1 Continue continue; It skips the current iteration and jumps to the next iteration.
Continue - Example
Creating Project
• Open Visual Studio 2019.
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();
}
}
Output
Goto
goto
1 Goto goto LabelName; It jumps to the specified label, within the same
method.
Goto - Example
Creating Project
• Open Visual Studio 2019.
• 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");
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• 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();
}
}
Output
o These are also imperative programming languages with control structures like if,
switch-case, while, do-while, for, break, continue, return etc.
o Ex: C
o These are also procedural programming languages with objects and classes.
• OOP is followed in almost-all modern programming languages such as C++, VC++, Java,
C#.NET, VB.NET etc.
• Advantages of OOP:
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.
Fields
Methods
Example:
Class
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.
• 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.
1. Memory will be allocated in RAM (Random Access Memory) for the object.
▪ Numerical Fields: 0
▪ Bool: false
• 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.
Example:
Reference variables
• 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.
class Classname
{
Class members here
}
Classname Referencevariablename ;
new Classname ( );
• 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.
Principles of OOP
1) Encapsulation
2) Abstraction
3) Inheritance
4) Polymorphism
Encapsulation:
• Fields are variables that stores the data; Methods are functions that manipulates
the data.
Abstraction:
Inheritance:
• As a result of inheritance, all the members of parent class are accessible in child
class.
Polymorphism:
Types of polymorphism:
▪ 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.
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.
1. private (default)
2. protected
3. internal
4. protected internal
5. public
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.
Creating Project
• Open Visual Studio 2019.
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
System.Console.WriteLine("Done");
System.Console.ReadKey();
}
}
}
Output
• Access Modifiers can be used for classes also, to specify where the class is accessible.
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.
Creating Project
• Open Visual Studio 2019.
• 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;
//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();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Student
{
public int StudentId;
public string StudentName;
public int Marks;
class Program
{
static void Main()
{
//create reference variables
Student s1, s2;
//create objects
s1 = new Student();
s2 = new Student();
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
System.Console.ReadKey();
}
}
Output
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”.
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).
Creating Project
• Open Visual Studio 2019.
• 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;
class Program
{
Console.ReadKey();
}
}
}
Output
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 by default “static”; so they are accessible without creating an object for
the class, using class name.
• Syntax:
Creating Project
• Open Visual Studio 2019.
Program.cs
class Sample
{
public const int NoOfMonthsInYear = 12;
}
class Program
{
static void Main()
{
System.Console.WriteLine(Sample.NoOfMonthsInYear);
System.Console.ReadKey();
}
}
Output
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.
• Syntax:
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.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
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();
}
}
Output
Methods
Methods
▪ The method is a “function” inside the class.
▪ 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”.
Creating Project
• Open Visual Studio 2019.
• 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();
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
Scope of Variables
Scopes of Variables
▪ “Life time” of the variable is called as “scope”.
1. Local variables:
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Person
{
public int age = 20;
class Program
{
static void Main()
{
Person p;
p = new Person();
System.Console.WriteLine(p.age);
p.Birthday();
System.Console.WriteLine(p.age);
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Class1
{
public double a, b;
public double sum;
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();
}
}
Output
Creating Project
• Open Visual Studio 2019.
Program.cs
class User
{
public string Username;
public string Password;
public string Message;
public void CheckLogin()
{
if (Username == "admin" && Password == "manager")
{
Message = "Successful login";
}
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();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• 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";
}
}
}
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();
s1.calculatetotalmarks();
s1.calculateaveragemarks();
s1.calculategrade();
s2.calculatetotalmarks();
s2.calculateaveragemarks();
s2.calculategrade();
System.Console.ReadKey();
}
}
Output
"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.
• 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.
Creating Project
• Open Visual Studio 2019.
• 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();
}
}
Output
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.
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.
Creating Project
• Open Visual Studio 2019.
• 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();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Person
{
public int age;
}
class Sample
{
public void Birthday(Person p)
{
p.age++;
}
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();
}
}
Output
• 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”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Hyderabad
{
public string Charminar = "Hyderabad.Charminar";
public string Golconda = "Hyderabad.Golconda";
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();
}
}
Output
Default Arguments
▪ 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.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
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.
▪ Syntax:
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Display(int x, int 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();
}
}
Output
Methods Overloading
▪ “Method Overloading” concept is “writing multiple methods with same name within the
same class, with different types 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.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
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”.
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”.
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” must be set to a value before the method definition ends.
▪ This is implemented using “out” keyword in both calling portion and receiving portion.
Creating Project
• Open Visual Studio 2019.
• 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
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• 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();
}
}
Output
Type Conversion
1. Implicit 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”.
Creating Project
• Open Visual Studio 2019.
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();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• 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;
//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();
}
}
Output
Parsing
▪ It is used to convert a value from “string” data type to “any numerical data type”.
▪ 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.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variable of "string" data type
string s = "100";
Output
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.
TryParse - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
TryParse – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create string and integer
string s = "hyderabad1234";
int n;
Output