C# Unit 2
C# Unit 2
1. VARIABLES:
- In C#, Variables will represent a storage location and each variable has a particular type that determines what type
of values can be stored in the variable.
- C# is a Strongly Typed programming language so before we perform any operation on variables, it’s mandatory to
define a variable with required data type to indicate what type of data that variable can hold in our application.
- Following is the syntax of declaring and initializing a variable in C# programming language.
[Data Type] [Variable Name];
[Data Type] [Variable Name] = [Value];
- If you observe above syntax, we added a required data type before the variable name to tell the compiler about
what type of data the variable can hold or which data type the variable belongs to.
- [Data Type] - It’s a type of data the variable can hold such as integer, string, decimal, etc.
[Variable Name] - It’s a name of the variable to hold the values in our application. [Value] -
Assigning a required value to the variable.
[Access Specifier] - It is used to define an access permission for the variable.
- Following are the some of valid ways to define the variable names in c# programming language. int abc;
float a2b;
char _abc;
- Following are the some of Invalid ways of defining the variable names in C# programming language.
int a b c; float 2abc;
char &abc; double
int;
• C# Multiple and Multi Line Variables Declaration:
- In c#, we can declare and initialize a multiple variables of same data type in a single line by separating with a
comma.
- Following is the example of defining the multiple variables of same data type in a single line by separating with
a comma in C# programming language.
int a, b, c;
float x, y, z = 10.5;
• C# Variables Assignment:
- In c#, once we declare and assign a value to the variable that can be assigned to another variable of same
data type.
- Following is the example of assigning a value of one variable to another variable of same type in C#
programming language.
int a = 123; int b = a;
string name = "suresh"; string firstname = name;
- In c#, it’s mandatory to assign a value to the variable before we use it otherwise we will get a compile time
errors.
- In case, if we try to assign a value of string data type to integer data type or vice versa like as shown below,
we will get an error like “cannot implicitly convert type int to string”.
int a = 123; string name = a;
2. C# Data Types:
- In C# programming language, Data Types are used to define a type of data the variable can hold such as
integer, float, string, etc. in our application.
- C# is a Strongly Typed programming language so before we perform any operation on variables, it’s
mandatory to define a variable with required data type to indicate what type of data that variable can hold in
our application.
- If you observe above syntax, we added a required data type before variable name to tell compiler about what
type of data the variable can hold or which data type the variable belongs to.
[Data Type] - It’s a type of data the variable can hold such as integer, string, decimal, etc.
[Variable Name] - It’s a name of the variable to hold the values in our application. [Value] -
Assigning a required value to the variable.
- Example:
namespace KLEBCA
{ class Program
{ static void Main(string[] args)
{ int number = 10;
string name = "Suresh Dasari"; double percentage = 10.23; char gender = 'M'; bool
isVerified = true;
}
}
}
- If you observe above c# data types example, we defined multiple variables with different data types based on
our requirements.
- Following diagram will illustrate more detail about different data types in c# programming language.
• C# Value Data Types:
- In c#, the Value Data Types will directly store the variable value in memory. In c#, the value data types will
accept both signed and unsigned literals.
- Following table lists the value data types in c# programming language with memory size and range of values.
3. C# keywords:
- In c#, Keywords are the predefined set of reserved words that have special meaning for the compiler.
- So the keywords in C# cannot be used as an identifiers such as variable name, class name, etc. in our
applications.
- C# Use Keywords as Variable Names: In case, if you want to use Keywords as variable names (identifiers),
then you need to include @ as a prefix for your variable names.
- For example, @switch is a valid identifier but switch is not because it’s a keyword and having a special
meaning for the compiler.
- Following is the example of using the reserve keywords as variable names by including @ as a prefix in C#
programming language.
using System;
namespace CsharpExamples
{ public class @class
{ public int age;
}
class Program
{ static void Main(string[] args)
{
- In c#, Operator is a programming element that specifies what kind of an operation need to perform on
operands or variables.
- For example, an addition (+) operator in C# is used to perform the sum operation on operands.
- These operators are categorized as a different group such as Binary Operators, Unary Operators and Ternary
Operators based on taking the number operands to perform the operations.
- Suppose, if operator that takes a one operand to perform the operation such as precedence operator (++), then
those will call as a Unary Operators.
- In case, if operator that takes a two operands to perform the operation such as arithmetic operator (-, +, *, /),
then those will call as a Binary Operators and we have a Ternary Operator that takes three operands to perform
the operation, such as conditional operator (?:).
- Example:
using System; namespace
KLEBCA
{ class Program
{ static void Main(string[] args)
{ int result;
int x = 20, y = 10; result = (x + y);
Relational Operators:
- Relational operators are used for comparison purpose in conditional statements.
- C# has following relational operators:
Operand Description
== Equality check
!= Un-equality check
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
- Example:
class Program
{ static void Main(string[] args)
{ bool result;
int x = 10, y = 20; result = (x == y);
Console.WriteLine("Equal to Operator: " + result); result = (x > y);
Console.WriteLine("Greater than Operator: " + result); result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result); result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result); Console.WriteLine("Press Enter Key to
Exit..");
Console.ReadLine();
}
}
Operand Description
& Bitwise AND
Bitwise OR
Bitwise XOR
! Bitwise NOT
&& “Logical” or “short circuit”
AND
“Logical” or “short circuit”
OR
- If we use Logical AND, OR operators in c# applications, those will return the result like as shown below for
different inputs.
- If you observe above table, if any one operand value become false, then the logical AND operator will return false,
same way the logical OR operator will return true, if any one operand value become true.
Assignment Operators:
- Assignment operators are use to assign values to variables.
- For example, we can declare and assign a value to the variable using assignment operator (=) like as shown below.
int a; a = 10;
Operand Description
= Simple assignment
+= Subtractive assignment
-= Multiplicative assignment
*= Division assignment
/= Division assignment
%= Modulo assignment
i. Postfix Operator:
- The increment operator ++ if used as prefix on a variable, the value of variable gets incremented by 1.
- After that the value is returned unlike Postfix operator.
- It is called Prefix increment operator. In the same way the prefix decrement operator works but it
decrements by 1.
Example:
output 51
51
51
using System;
class Program
{ static void Main()
{ int a, b; a = 10;
Console.WriteLine(a++);
b = a; Console.WriteLine(a); Console.WriteLine(b); }
}
Output:
10
11
12
- Example:
using System;
namespace DEMO
{ class Program
{ static void Main(string[] args)
{ int a, b; a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b); b = (a ==
10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b); Console.ReadLine();
}
}
}
Output:
Value of b is 30 Value of b is 20
Operators Precedence:
- In c#, Operators Precedence is used to define a multiple operators in single expression and the evaluation of
expression can be happened based on the priority of operators.
- For example, the multiplication operator (*) is having a higher precedence than the addition operator (+).
- So if we use both multiplication (*) and addition (+) operators in single expression, first it will evaluate the
multiplication part and then the addition part in expression.
int i = 3 + 4 * 5;
- When we execute above statement, first the multiplication part (4 * 5) will be evaluated.
- After that the addition part (3 + 12) will be executed and i value will become a 23.
- As said earlier, multiplication (*) operator is having a higher precedence than addition (+) operator so first
multiplication part will be executed.
Flow Control
– Looping in a programming language is a way to execute a statement or a set of statements multiple times
depending on the result of the condition to be evaluated to execute statements.
– The result condition should be true to execute statements within loops.
– Loops are mainly divided into two categories:
1. while loop:
- The test condition is given in the
beginning of the loop and all
statements are executed till the
given boolean condition satisfies
when the condition becomes false,
the control will be out from the
while loop.
- Syntax: while (boolean condition)
{ loop statements...
}
2. for loop:
- for loop has similar functionality as while loop but with different syntax. for loops are preferred when
the number of times loop statements are to be executed is known beforehand.
- The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is
done in one line in for loop thereby providing a shorter, easy to debug structure of looping.
- Syntax:
for (loop variable initialization ; testing condition; increment / decrement) {
// statements to be executed
}
1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is
the starting point of for loop. An already declared variable can be used or a variable can be declared,
local to loop only.
2. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit
condition for a loop. It must return a boolean value true or false. When the condition became false the
control will be out from the loop and for loop ends.
3. do-while loop:
- do while loop is similar to while loop with the only difference that it checks the condition after
executing the statements, i.e it will execute the loop body one time for sure because it checks the
condition after executing the statements.
- Syntax : do
{ statements..
}while (condition);
Conditional Statements
– Decision Making in programming is similar to decision making in real life.
– In programming too, a certain block of code needs to be executed when some condition is fulfilled.
– A programming language uses control statements to control the flow of execution of program based on
certain conditions.
– These are used to cause the flow of execution to advance and branch based on changes to the state of a
program.
1. IF Statement
- The if statement checks the given condition. If the condition evaluates to be true then the block of
code/statements will execute otherwise not.
- Syntax:
if(condition)
{
//code to be executed }
– Note: If the curly brackets { } are not used with if statements than the statement just next to it is only
considered associated with the if statement.
– Example:
if (condition) statement 1;
statement 2;
– In this example, only statement 1 is considered to be associated with the if statement.
2. IF – else Statement
- The if statement evaluates the code if the condition is true but what if the condition is not true, here
comes the else statement.
- It tells the code what to do when the if condition is false.
- Syntax: if(condition)
{
// code if condition is true
} else
{
// code if condition is false }
4. Switch Statement
- Switch statement is an alternative to long if-else-if ladders.
- The expression is checked for different cases and the one match is executed.
- break statement is used to move out of the switch.
- If the break is not used, the control will flow to all cases below it until break is found or switch comes to an
end.
- There is default case (optional) at the end of switch, if none of the case matches then default case is
executed.
- Syntax:
switch (expression)
{ case value1: // statement sequence break;
case value2: // statement sequence break;
.
.
.
case valueN: // statement sequence break;
default: // default statement sequence
}
Object And Classes: In c#, Classes and Objects are interrelated. The class in c# is
nothing but a collection of various data members (fields, properties, etc.) and member
functions. The object in c# is an instance of a class to access the defined properties and
methods.
Class: In c#, Class is a data structure and it will combine a various types of data
members such as fields, properties, member functions and events into a single unit.
Declaring a Class in C#:In c#, classes are declared by using class keyword. Following is the
declaration of class in c# programming language.
If you observe above syntax, we defined a class “users” using class keyword with public access
modifier. Here, the public access specifier will allow the users to create an objects for this class
and inside of the body class, we can create a required fields, properties, methods and events to
use it in our applications.
C# Class Example:
If you observe above image, we used a various data members like access modifiers, fields,
properties, methods, constructors, etc. in our c# class based on our requirements.
C# Class Members:
C# Object:
Generally, we can say that objects are the concrete entities of classes. In c#, we can create an
objects by using a new keyword followed by the name of the class like as shown below.
If you observe above example, we created an instance (user) for the class (Users) which we
created in previous section. Now the instance “user” is a reference to an object that is based on
Users. By using object name “user” we can access all the data members and member functions
of Users class.
Object Example:
class Program
{
static void Main(string[] args)
{
Users user = new Users("Suresh Dasari", 30);
user.GetUserDetails();
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
public class Users
{
public string Name { get; set; }
public int Age { get; set; }
public Users(string name, int age)
{
Name = name;
Age = age;
}
public void GetUserDetails()
{
Console.WriteLine("Name: {0}, Age: {1}", Name, Age);
}
}
If you observe above example, we created a new class called “Users” with a required data
members and member functions. To access Users class methods and properties, we created an
object (user) for Users class and performing required operations.
When we execute above c# program, we will get the result like as shown below.
ACCESS MODIFIERS:
Access Modifiers are the keywords which are used to define an accessibility level for all types and type
members.
By specifying an access level for all types and type members, we can control that whether they can be
accessed in other classes or in current assembly or in other assemblies based on our requirements.
Following are the different type of access modifiers available in c# programming language.
Public
Private
Protected
Internal
Properties (GET, SET):
In c#, Property is an extension of class variable and it provides a mechanism to read, write or
change the value of class variable without effecting the external way of accessing it in our
applications.
In c#, properties can contain one or two code blocks called accessors and those are called a get
accessor and set accessor. By using get and set accessors, we can change the internal
implementation of class variables and expose it without effecting the external way of accessing
it based on our requirements.
Generally, in object oriented programming languages like c# we need to define a fields as private,
and then use properties to access their values in public way with get and set accessors.
Following is the syntax of defining a property with get and set accessor in c# programming
language.
{
// set a new value
}
}
Static Methods
You can define one or more static methods in a non-static class. Static
methods can be called without creating an object. You cannot call static
methods using an object of the non-static class.
The static methods can only call other static methods and access static
members. You cannot access non-static members of the class in the static
methods.
class Program
{
static int counter = 0;
string name = "Demo Program";
SetRootFolder("C:\MyProgram");
//Error: cannot call non-static method
}
1. Static methods can be defined using the static keyword before areturn
type and after an access modifier.
2. Static methods can be overloaded but cannot be overridden.
3. Static methods can contain local static variables.
4. Static methods cannot access or call non-static variables unless theyare
explicitly passed as parameters.
Constructor in C#:
In c#, Constructor is a method which will invoke automatically whenever an instance of class or
struct is created. The constructor will have a same name as the class or struct and it useful to
initialize and set a default values for the data members of the new object.
In case, if we create a class without having any constructor, then the compiler will automatically
create a one default constructor for that class. So, there is always one constructor will exist in
every class.
In c#, a class can contain more than one constructor with different type of arguments and the
constructors will never return anything, so we don’t need to use any return type, not even void
while defining the constructor method in class.
SYNTAX:
As discussed, constructor is a method and it won’t contain any return type. If we want to create
a constructor in c#, then we need to create a method whose name is same as the class name.
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor
Default Constructor: In c#, if we create a constructor without having any parameters, then we
will call it as default constructor and the every instance of class will be initialized without any
parameter values.
Parameterized Constructor: In c#, if we create a constructor with at least one parameter, then
we will call it as parameterized constructor and the every instance of class will be initialized with
parameter values.
class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}
class Program
{
static void Main(string[] args)
{
// The constructor will be called automatically once the
instance of class created
User user = new User("Suresh Dasari", "Hyderabad");
Console.WriteLine(user.name);
Console.WriteLine(user.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
If you observe above example, we created a class called “User” and the constructor method
“User(string, string)” with parameters. When we create an instance of our class (User) with
required parameters, then automatically our constructor method will be called.
When we execute above c# program, we will get the result like as shown below.
If you observe above result, our constructor method has called automatically and initialized the
parameter values after creating an instance of our class with required parameters.
Constructor Overloading:
In c#, we can overload the constructor by creating another constructor with same method
name but with different parameters.
Example:
using System;
namespace Tutlane
{
class User
{
public string name, location;
// Default Constructor
public User() {
name = "Suresh Dasari";
location = "Hyderabad";
}
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}
class Program
{
static void Main(string[] args)
{
User user = new User(); // Default Constructor will be called
User user1 = new User("Rohini Alavala", "Guntur"); //
Parameterized Constructor will be called
Console.WriteLine(user.name + ", " + user.location);
Console.WriteLine(user1.name + ", " + user1.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we created a class called “User” and overloaded a constructor
“User()” by creating another constructor “User(string, string)” with same name but with different
parameters.
When we execute above c# program, we will get the result like as shown below.
If you observe above result, the respective constructor methods will be called automatically when we
create an instance of our class with or without parameters based on our requirements.
In simple words, we can say copy constructor is a constructor which copies a data of one object
into another object. Generally, c# won’t provide a copy constructor for objects but we can
implement ourselves based on our requirements.
Static Constructor:
In c#, Static Constructor is used to perform a particular action only once throughout the
application. If we declare a constructor as static, then it will be invoked only once irrespective of
number of class instances and it will be called automatically before the first instance is created.
using System;
namespace Tutlane
{
class User
{
// Static Constructor
static User()
{
Console.WriteLine("I am Static Constructor");
}
// Default Constructor
public User()
{
Console.WriteLine("I am Default Constructor");
}
}
class Program
{
static void Main(string[] args)
{
// Both Static and Default constructors will invoke for first
instance
User user = new User();
// Only Default constructor will invoke
User user1 = new User();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above result, for the first instance of class both static and default constructors
execute and for the second instance of class only default constructor has executed.
This is how we can use static constructor in c# programming language to execute particular
action only once throughout the application based on our requirements.
Private Constructor:
In c#, Private Constructor is a special instance constructor and it is used in a classes that
contains only static members. If a class contains one or more private constructors and no public
constructors, then the other classes are not allowed to create an instance for that particular class
except nested classes.
Destructors
.Net will clean up the un-used objects by using garbage collection process. It internally uses the
destruction method to clean up the un-used objects. Some times the programmer needs to do
manual cleanup.
Syntax
~<ClassName>
{}
Sample Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BRK.ConstructorExample
{
class Welcome
{
// Default constructor
public Welcome()
{
Console.WriteLine("Welcome message from Default
Constructor...");
}
// Destructor
~Welcome()
{
Console.WriteLine("Destructor called");
}
}
class Program
{
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default constructor
Welcome obj = new Welcome();
Console.Read();
}
}
}
Method Overloading: In c#, Method Overloading means defining a multiple methods with
same name but with different parameters. By using Method Overloading, we can perform a
different tasks with same method name by passing different parameters.
Suppose, if we want to overload a method in c#, then we need to define another method with
same name but with different signatures. In c#, the Method Overloading is also called as
compile time polymorphism or early binding.
Example:
using System;
namespace Tutlane
{
public class Calculate
{
public void AddNumbers(int a, int b)
{
Console.WriteLine("a + b = {0}", a + b);
}
public void AddNumbers(int a, int b, int c)
{
Console.WriteLine("a + b + c = {0}", a + b + c);
}
}
class Program
{
static void Main(string[] args)
{
Calculate c = new Calculate();
c.AddNumbers(1, 2);
c.AddNumbers(1, 2, 3);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
C# .NET