0% found this document useful (0 votes)
3 views

Chapter-5

Uploaded by

Suseela Devi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter-5

Uploaded by

Suseela Devi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

5.

More about Variables


TYPE CONVERSION:
 Type conversion is used to convert the values of one data type into another data type.
 Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#,
type casting has two forms −
 Implicit type conversion − These conversions are performed by C# in a type-safe manner.
 Explicit type conversion − These conversions are done explicitly by users using the pre-defined
functions. Explicit conversions require a cast operator.
Implicit conversion:- The C# compiler implicitly converts the value of one data type to another type
without any loss of data.
It happens when:
 The two data types are compatible.
 When we assign value of a smaller data type to a bigger data type.
Ex:- char var1 = ‘s’;
int var2 = var1;
Ex2: short a = 20;
int b = a;
For Example, in C#, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or Boolean.
Also, char and Boolean are not compatible with each other.
Before converting, the compiler first checks the compatibility according to the following figure
and then it decides whether it is alright or there some error.

Following table shows the implicit types of conversion that is supported by C# :

CONVERT FROM DATA TYPE CONVERT TO DATA TYPE

byte short, int, long, float, double

short int, long, float, double


int long, float, double
long float, double
float double
// C# program to demonstrate the Implicit Type Conversion
using System;
namespace Casting {
class GFG {
public static void Main(String []args) // Main Method
{
int i = 57;
long l = i; // automatic type conversion
float f = l; // automatic type conversion
Console.WriteLine("Int value " +i); // Display Result
Console.WriteLine("Long value " +l);
Console.WriteLine("Float value " +f);
}
}
}
Explicit Conversions :
 An explicit conversion occurs when we explicitly ask the compiler to convert a value from
one data type to another.
 We can perform an explicit conversion through casting. Casting means forcing data from
one type into another.
using System;
namespace Casting {
class Program {
public static void Main(String []args)
{
double d = 765.12;
int i = d;
Console.WriteLine("Value of i is ", +i);
}
} }
There may be compilation error when types not compatible with each other. For example,
. So, if we want to assign a value of larger data type to a smaller data type we perform explicit
type casting
 This is useful for incompatible data types where automatic conversion cannot be done.
Syntax: <(destinationType)sourceVar>
This will convert the value in <sourceVar> into <destinationType>.
Ex: float a = 24.5F;
int b = (int) a;
public static void Main(String []args)
{
double d = 765.12;
int i = (int)d; // Explicit Type Casting
Console.WriteLine("Value of i is " +i);
}
Explicit Conversions Using the Convert Commands
C# provides built-in methods for Type-Conversions, by using these methods we have been
converting one type to other type.
using System;
namespace Casting {
class Program {
public static void Main(String []args)
{
int i = 12;
double d = 765.12;
float f = 56.123F;
Console.WriteLine(Convert.ToString(f));
Console.WriteLine(Convert.ToInt32(d));
Console.WriteLine(Convert.ToUInt32(f));
Console.WriteLine(Convert.ToDouble(i));
}
} }
Output:
56.123
765
56
12
COMPLEX VARIABLE TYPES:
C# offers 3 types of complex variable types.
1. Enumerations (often referred to as enums)
2. structs (occasionally referred to as structures)
3. arrays.
Enumerations:-
 Enumeration is a user-defined data type. A set of named constant values are referred as
enumeration.
 It is a set of named integer constants. Or enumerations are special set of named values
which all map to a set of numbers, usually integers.
 An enumerated type is declared using the enum keyword.
 To represent group of named constants we should go for enum. Ex: to represent month
names under single name use enum.
 We can define enum inside a namespace , class or structure. But it is better to define an
enum directly the namespace.
Defining Enumerations
We can use the enum keyword to define enumerations as follows:
enum <typeName>
{
<value1>,
<value2>,
<value3>,
...
<valueN>
}
Next, we can declare variables of this new type as follows:
<typeName> <varName>;
You can assign values using the following:
<varName> = <typeName>.<value>;
using System;
namespace Enumerations
{
enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
class Program
{
static void Main(string[] args)
{
Days day = Days.Monday;
if (day == Days.Monday)
{
Console.WriteLine("It is Monday");
}
Console.WriteLine(day);
}
} }
Out put: It is Monday
Monday
Structs:-
 The struct (short for structure)is a user defined data type.
 Structure collection of variables of different data types under a single unit.
 It is almost similar to a class because both are user-defined data types and both hold a
bunch of different data types.
 In C#, structure is defined using struct keyword.
 Using struct keyword one can define the structure consisting of different data types in it.
 In C#, structures can contain most of the members what a class can contain like Fields,
methods, constructors, properties, etc…
Defining Structs
Structs are defined using the struct keyword as follows:
struct <typeName>
{
<memberDeclarations>
}
Structs:-
The <memberDeclarations> section contains declarations of variables (called the data
members of the struct)
Each member declaration takes the following form:
<accessibility> <type> <name>;
To allow the code that calls the struct to access the struct’s data members,
we use the keyword public for <accessibility>.
For example:
struct route
{
public string direction;
public double distance;
}
Once you have a struct type defined, we use it by defining variables of the new type:
route myRoute;
In addition, we have access to the data members of this composite variable via the period character
myRoute.direction = north;
myRoute.distance = 2.5;
Structs:-
using System;
namespace ConsoleApplication {
public struct Person // Defining structure
{
public string Name;
public int Age;
public int Weight;
}
class Sample {
static void Main(string[] args)
{
Person P1; // Declare P1 of type Person
P1.Name = "Keshav Gupta";
P1.Age = 21;
P1.Weight = 80;
Console.WriteLine("Data Stored in P1 is "+
P1.Name + ,age is " +
P1.Age + " and weight is " +
P1.Weight);
}
} }
Difference between Class and Structure

Class Structure

Classes are of reference types. Structs are of value types.


All the reference types are allocated All the value types are allocated on
on heap memory. stack memory.
Class can be inherited We can’t inherit the structure.
Object creation is mandatory Optional
New keyword is used to create object
for the class
Arrays:
Array is used to store several values of the same type under single name.
Declaring Arrays
Arrays are declared in the following way:
<Type>[ ] <name>;
Here, <Type> may be any variable type.
Arrays must be initialized before we have access to them.
int[ ] a;
2 ways to initialize the arrays
• Specifying an array using literal values simply involves providing a comma-separated list of
element values enclosed in curly braces:
• int[] a= { 5, 9, 10, 2, 99 }; Here, a has five elements, each with an assigned integer value.
• The other method requires the following syntax:
• int[] a = new int[5];
• Here, you use the new keyword to explicitly initialize the array, and a constant value to define
the size.
• This method results in all the array members being assigned a default value, which is 0 for
we can also use nonconstant variables for this initialization:
int[] a = new int[arraySize];
In addition, we can combine these two methods of initialization if we want:
int[] a = new int[5] { 5, 9, 10, 2, 99 };
With this method the sizes must match.
we can’t, for example, write the following:
int[] a = new int[10] { 5, 9, 10, 2, 99 };
Here, the array is defined as having 10 members, but only five are defined,
so compilation will fail.
• there is no need to initialize an array on the same line that you declare it.
• The following is perfectly legal:
• int[] a;
• a = new int[5];
C# array is an object of base type System. Array.
C# program to illustrate creating an array of integers, puts some values in the array, and prints each value to
standard output.
using System;
namespace example {
class Program {
public static void Main()
{
int[] a;
a = new int[5]; // allocating memory for 5 integers.
a[0] = 10; // initialize the first elements of the array
a[1] = 20; // initialize the second element
a[2]= 30;
a[3]= 40;
a[4]= 50;
// accessing the elements using for loop
for (int i = 0; i <a.Length; i++)
Console.Write( a[i]);
// using for-each loop
foreach(int i in a)
Console.Write( i);
Foreach Loop:-
This Loop Enables you to address each element in an array.
Syntax: foreach(<type> <name> in <array>)
foreach gives you read-only access to the array contents, so you can’t change
the values of any of the elements.
foreach (string friendName in friendNames)
{
}
Ex: foreach(int i in a)
Multidimensional Arrays
A multidimensional array is simply one that uses multiple indices to
access its elements.
A two-dimensional array such as this is declared as follows:
<Type>[,] <name>;
Arrays of more dimensions simply require more commas:
<type>[ , ] <name> = new datatype[2,2];
double[,] hillHeight = new double[3,4];
Alternatively, you can use literal values for initial assignment.
Here, you use nested blocks of curly braces, separated by commas:
double[,] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };

To access individual elements of a multidimensional array, you simply specify the indices
separated by commas:
hillHeight[2,1]
The foreach loop gives you access to all elements in a multidimensional way, just as with
singledimensional arrays:
double[,] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };
foreach (double height in hillHeight)
{
Console.WriteLine("{0}", height);
Arrays of Arrays:-
A jagged array is an array of array. Jagged arrays store arrays instead of literal
values.
A jagged array is initialized with two square brackets [][].
The first bracket specifies the size of an array, and the second bracket specifies the
dimensions of the array which is going to be stored.

int[][] jArray1 = new int[2][]; // can include two single-dimensional arrays

int[][,] jArray2 = new int[3][,]; // can include three two-dimensional arrays


STRING MANIPULATION:
Def: In C#, string is an object of System.String class that represent sequence of
characters.
We can perform many operations on strings such as concatenation, comparison,
getting substring, search, trim, replacement etc.
• string vs String
• In C#, string is keyword which is an alias for System.String class. That is why
string and String are equivalent. We are free to use any naming convention.
• string s1 = "hello";//creating string using string keyword
• String s2 = "welcome";//creating string using String class
Properties of String Class:
Length: Used to get the number of characters in the current String object.
Methods:
It has numerous methods that help you to working with string object.
Compare(string, string): It is used to compares two specified String objects. It returns an integer
that indicates their relative position in the sort order.
Concat(String, String): It is used to concatenate two specified instances of String.
Contains(string): It is used to return a value indicating whether a specified substring occurs
within this string.
Replace(String, String): It is used to return a new string in which all occurrences of a specified
string in the current instance are replaced with another specified string.
Substring (Int32): It is used to retrieve a substring from this instance. The substring starts at a
specified character position and continues to the end of the string.
ToLower(): It is used to convert String into lowercase.
ToUpper(): It is used to convert String into uppercase.
ToString(): It is used to return instance of String

You might also like