C# Unit-2
C# Unit-2
Notes of Unit-2
• We know that while developing any software application using c#; we will be
dealing with different types of data and data values. In order to store and process
different types of data & data values computer uses its memory(RAM). To
allocate a chunk of memory and access it within a C# program, We need to
declare a variable.
• Declaring a variable:
Before using local variable it has to be assigned or initialized with some meaningful
value.
Ex:
a = 0;
Example
using System;
namespace VariableDemo
{
class Program
{
public static void Main(string[] args)
{
int a=0;
int b=10;
C# Data Types:
The Understanding Value Types and Reference 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.
it’s mandatory to define a variable with required data type to indicate what type of data
that variable can hold in our application.
Value Type
All fixed length data types int, float, char etc. will come under the category of value type.
Reference Type
All variable length data types like string and object will comes under the category of
reference types.
Eg:
int a;
int a=10;
[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:
using System;
namespace DatatypeDemo
{
class Program
{
public static void Main(string[] args)
Relational Operators
Logical Operators
Bitwise Operators
Arithmetic Operators
using System;
namespace BCA
{
class Program
{
public static void Main(string[] args)
{
int result;
int x = 20, y = 10;
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
result = (x / y);
int age=56;
Salary=9000;
• If (age>55 && salary<1000)
• For example −
b = (a == 1) ? 20 : 30;
• Above, if the first operand evaluates to true (1), the second operand is evaluated.
If the first operand evaluates to false (0), the third operand is evaluated
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=10;
INCREMENT AND DECREMENT OPERATORS:
• PREFIX NOTAION: 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.
using System;
namespace BCA
{
class Program
{
static void Main(string[] args)
{
int a, b;
a = 50;
Console.WriteLine(++a);
b = a;
Console.WriteLine(a);
Console.WriteLine(b);
}
Prof. Raju Vathari Page 9
}
}
Postfix Operator:
• The increment operator ++ if used as postfix on a variable, the value of variable is
first returned and then gets incremented by 1. It is called Postfix increment
operator. In the same way the decrement operator works but it decrements by 1.
namespace BCA
{
class Program
{
public static void Main(string[] args)
{
int a, b;
a = 10;
Console.WriteLine(a++);
b = a;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
}
C# if statement
• Use the if statement to specify a block of C# code to be executed if a condition
is True.
if (expression)
{
C# While Loop
The while loop loops through a block of code as long as a specified condition is True:
while (condition)
{
// code block to be executed
}
using system;
class Program
{
public static void Main(string[] args)
{
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
For loop
• When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax
Example:
using system;
Class Program
{
public static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
}
}
Example:
using system;
class Program
{
public static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
Console.ReadLine();
}
}
}
Concept of a class:
In C#, a class is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors, etc.
class Student
{
int id;//field or data member
String name;//field or data member
}
Object
In C#, an Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, the object is an entity that has a state and behaviour. Here, state means
data and behaviour means functionality.
Object is an instance of a class. All the members of the class can be accessed through
object.
In this example, Student is the type and s1 is the reference variable that refers to the instance of
the Student class. The new keyword allocates memory at runtime.
Let's see an example of a class that has two fields: id and name. It creates an instance of
the class, initializes the object, and prints the object value.
using System;
public class Student
{
int id; //data member (also instance variable)
String name; //data member (also instance variable)
public static void Main(string[] args)
{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Virat";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
Let's see another example of a class where we are having Main() method in another
class. In such cases, a class must be public.
using System;
public class Student
{
public int id;
public String name;
}
class TestStudent
{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.id = 101;
s1.name = "Virat";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
class Student
{
// fields contained in Student class
string name;
int age;
intmarksInMaths;
intmarksInEnglish;
intmarksInScience;
inttotalMarks = 300; // initialization
intobtainedMarks;
double percentage;
}
You can also initialize the fields with the initial values as we did in totalMarks in the
example above. If you don't initialize the members of the class, they will be initialized
with their default values.
Access Modifiers are the keywords which are used to define an accessibility level
for all types and typemembers.
By specifying an access level for all types and type members, we can control that
whether they can be
accessedinotherclassesorincurrentassemblyorinotherassemblies
basedonourrequirements.
Followingarethedifferenttypeofaccessmodifiersavailableinc#programminglanguage.
Public
Private
Protected
Internal
Protected internal
The keyword static implies that only one instance of the member exists for a class.
Static variables are used for defining constants because their values can be retrieved by
invoking the class without creating an instance of it. Static variables can be initialized
outside the member function or class definition. You can also initialize static variables
inside the class definition.
Example
using System;
namespace staticmembers
{
class StaticVar
{
public static intnum;
public intgetNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
Output:
C# Constructor
Constructor is a special method present under a class responsible for initializing the
variables of the class.
The name of the constructor method is exactly the same name of the class in which it
was present.
Each and every class must have the constructor if we want to create the instance of that
class.
o Default constructor
o Parameterized constructor
C# Default Constructor
A constructor which has no argument is known as the default constructor. It is invoked
at the time of creating an object.
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
}
class TestEmployee
{
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
Console.ReadLine();
}
}
Output:
C# Parameterized Constructor
A constructor which has parameters is called a parameterized constructor. It is used to
provide different values to distinct objects.
using System;
publicclassEmployee
{
publicint id;
publicString name;
public Employee(inti, String n)
{
id = i;
name = n;
}
publicvoid display()
{
Console.WriteLine(id + " " + name);
}
}
classTestEmployee
{
publicstaticvoid Main(string[] args)
{
Employee e1 = newEmployee(101, "ABC");
Employee e2 = newEmployee(102, "EFG");
e1.display();
e2.display();
Console.ReadLine();
}
}
Output:
101 ABC
102 EFG
Destructors
Important Points:
A Destructor is unique to its class i.e. there cannot be more than one destructor in a
class.
A Destructor has no return type and has exactly the same name as the class name
(Including the same case).
It is distinguished apart from a constructor because of the Tilde symbol (~) prefixed
to its name.
A Destructor does not accept any parameters and modifiers.
It cannot be defined in Structures. It is only used with classes.
It cannot be overloaded or inherited.
It is called when the program exits.
Internally, Destructor called the Finalize method on the base class of object.
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Constructor Invoked");
}
~Employee()
{
Console.WriteLine("Destructor Invoked");
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
Method Overloading
Having two or more methods with same name but different in parameters, is
known as method overloading in C#.
The advantage of method overloading is that it increases the readability of the program
because you don't need to use different names for same action.
Let's see the simple example of method overloading where we are changing number of
arguments of add() method.
using System;
public class Cal
{
public static int add(int a,int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
Output:
35
65
Let's see the another example of method overloading where we are changing data type
of arguments.
using System;
public class Cal
{
public static int add(int a, int b)
{
return a + b;
}
public static float add(float a, float b)
{
return a + b;
}
}
public class TestMemberOverloading
{
public static void Main()
{
Console.WriteLine(Cal.add(12, 23));
Output:
35
33.7