Language Basics Cs
Language Basics Cs
Language Basics Cs
Services Basics
Agenda
Table Of Contents
1
Deccansoft Software Language Chapter-3
Services Basics
2
Deccansoft Software Language Chapter-3
Services Basics
3
Deccansoft Software Language Chapter-3
Services Basics
2. Stack Memory: Used by local variables of a method. When a method is invoked a stack of memory
is allocated to and the stack is cleared when the method returns
3. Heap Memory: All dynamic memory requirements of an application are fulfilled from the heap
memory. After allocating some memory from heap to a variable, once its job is completed the memory
must be returned back to heap so that the same can be reused for another variable.
The value type of variable has value where as the value of a reference type is reference to
value (object) on heap.
The value (object) of a reference type is always allocated heap memory.
Value types are allocated memory based on the scope of the variable, If its Global Variable its
allocated memory in Global Memory Area, if its Local Variable or Parameter its allocated memory on
stack and if it’s a member of an object its allocated memory on Heap.
Value Types directly hold the value. Ex: All Basic Types, Structures & Enum
ValueType
Reference Types hold the reference to the value on HEAP. Var = Value Value
Ex: String, Object, Class, Arrays, Delegates Ref
Var
4
Deccansoft Software Language Chapter-3
Services Basics
5
Deccansoft Software Language Chapter-3
Services Basics
Fig: 3.1
6
Deccansoft Software Language Chapter-
Note:
You cannot use the checked and unchecked keywords to control floating point (non-‐integer)
arithmetic. The checked and unchecked keywords control only integer arithmetic. Floating point
arithmetic never throws OverflowException.
7
Deccansoft Software Language Chapter-
Program to Print the Char equivalent of the Ascii value read from the keyboard
using System;
class Program
{
static void Main(string[] args)
{
string str;
str = Console.ReadLine();
int n = 100;
if (int.TryParse(str, out n))
Console.WriteLine((char)n);
else
Console.WriteLine("Invalid number");
}
}
Code: 3.2 C#
8
Deccansoft Software Language Chapter-
object obj =
n; //Boxing n = (int)
1 When a value is boxed to an object type, the object type variable cannot be used in any
mathematical operations.
2 When the value of object type variable cannot be assigned to variable on LHS, an Exception of
type InvalidCastException is thrown.
3 Excessive usage of Object data type makes the language “Loosely Typed” and also because of
frequent casting requirement while Boxing and Unboxing performance is also degraded.
4 Boxing / Unboxing should be used only in situations where until runtime we don’t know the type
of data we are going to deal with.
9
Deccansoft Software Language Chapter-
n = 2; //n is int
WeekDay wd = WeekDay.Sat; wd = (WeekDay) n; //Explicit
//n = wd; //Invalid
n = (int) wd; //Explicit -‐ In VB.NET it’s not required
//Constant Declaration
const double PI = 3.14;
1
Deccansoft Software Language Chapter-
Operators
Dividing a Integral Type with zero (Integral Division Operator) throws DivideByZeroException
Floating Point Division by zero is not a runtime exception but the value would be either PositiveInfinity
(if numerator is greater than zero) or NegativeInfinity (if numerator is less than zero) or NaN (if
numerator is also zero)
1
Deccansoft Software Language Chapter-
Control Statements
If else-‐statement syntax:
if (BooleanExpression)
{
statement;
}
else if (Boolean-‐Expression)
{
statement;
}
else
{
statement;
}
Program to print if the command line argument provided is an odd number or even number
using System;
using System;
class Program
{
public static void Main(string[] args)
{
int n;
if (args.Length == 0)
Console.WriteLine("Please provide a number");
else if (!int.TryParse(args[0], out n))
Console.WriteLine("Not a number");
else if (int.Parse(args[0]) % 2 == 0)
Console.WriteLine("Even number");
else
Console.WriteLine("Odd number");
}
}
Code: 3.3 C#
Note:
To execute above program correctly, supply valid integers in command line arguments. Right
click on Project -‐> Select Properties -‐> Click on Debug tab and enter few values in “Command line
arguments” section seperated by spaces. For this example we have used the values: 2 3
1
Deccansoft Software Language Chapter-
Fig: 3.2
Task:
Write a program
while…..loop to print
statement grade of the person based on the marks scored.
syntax:
while (BooleanExpression)
{
Statements;
}
do
{
Statements
}
while (BooleanExpression)
}
13
Deccansoft Software Language Chapter-
Program to Print the table of any number read from the keyboard.
using System;
class Program
{
public static void Main()
{
int n;
Console.Write("Table of: ");
n = int.Parse(Console.ReadLine());
string s = "";
for (int i = 1; i <= 10; i++)
s += n + "*" + i + "=" + n * i + "\n";
Console.WriteLine(s);
}
}
Code: 3.4 C#
Fig: 3.3
for statement syntax:
for ( initializer; condition; iterator )
{
statements;
}
1
Deccansoft Software Language Chapter-
{
for (int j = 0; j < 3; j++)
{
if (i == j)
break;
Console.WriteLine(i + " " + j);
}
}
}
}
Code: 3.5 C#
Fig: 3.4
1
Deccansoft Software Language Chapter-
Fig: 3.5
Fig: 3.6
1
Deccansoft Software Language Chapter-
17
Deccansoft Software Language Chapter-
Single-‐Dimensional Arrays
int [] myArray = new int [5];
string []myStringArray = new string[5];
When you initialize an array upon declaration, it is possible to use the following shortcuts: int[] myArray = {1, 3, 5, 7, 9};
string[] weekDays = {"Sun", "Sat", "Mon", "Tue"};
It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array
int[] myArray;
myArray = new int[] {1, 3, 5, 7, 9}; // OK
myArray = {1, 3, 5, 7, 9}; // Error
weekdays = new string[] {“Sunday”, “Monday”, “Tuesday”};
Multi-‐Dimensional Arrays
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3: int[,,] myArray = new int [4,2,3];
You can initialize the array upon declaration as shown in the following example: int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6},
You can also initialize the array without specifying the rank:
int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the vari
int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK
myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error
1
Deccansoft Software Language Chapter-
Console.WriteLine(n);
}
}
Code: 3.9 C#
Fig: 3.7
Program: To read a list of numbers separated by space and print the Average of all those
numbers.
using System;
class ProgramForMaxOfAnyNumbers
{
static void Main(string[] args)
{
string str = Console.ReadLine();
string[] ar = str.Split(' ');
int sum = 0;
for (int i = 0; i < ar.Length; i++)
{
sum += int.Parse(ar[i]);
Console.WriteLine(ar[i]);
}
Console.WriteLine("Average: " + 1.0 * sum / ar.Length);
}
}
Code: 3.10 C#
1
Deccansoft Software Language Chapter-
Fig: 3.8
Program: To read length and data for an array from keyboard print the same.
using System;
class ProgramForMaxOfAnyNumbers
{
static void Main()
{
Console.Write("Enter the array length: ");
int n;
n = int.Parse(Console.ReadLine());
int[] ar = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Enter the " + i + "th value: ");
ar[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < ar.Length; i++)
{
Console.Write(ar[i] + " ");
}
}
}
Code: 3.11 C#
2
Deccansoft Software Language Chapter-
Fig: 3.9
2
Deccansoft Software Language Chapter-
Working with
Method Overloading:
1 Having two or more methods with same name and different parameters.
2 Parameters must be different either in their data type or in their count.
3 Method cannot be overloaded based on Return Type or ByVal/ByRef or Parameter names.
4 Call to the Overloaded method is resolved at compile time and is done based on data type and count
of arguments passed to the method.
5 While resolving the called method, the compiler searches for a direct match of arguments and
parameters. Only if a direct match is not available it would then use nearest match for resolving the
call.
Method overloading
using System;
class Program
{
public static void Main()
{
int res = Add(10, 2);
Console.WriteLine(res.ToString());
string str;
str = Add("Deccan", "soft");
Console.WriteLine(str);
}
static int Add(int a, int b)
{
return Add(a, b, 0);
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static string Add(string s1, string s2)
{
return s1 + s2;
}
}
Code: 3.12 C#
22
Deccansoft Software Language Chapter-
Fig: 3.10
Params Parameters:
1. Only Parameters which are of type array (of any data type) can be declared as params
2. If parameter is declared as params either a reference to the array can be passed as argument or 0
or more individual values can be passed to it.
3. Only one parameter of a method can be declared as params parameter.
4. It must be last parameter in the list of parameters for a given method.
5. If we have other parameters in the list they must be before the params parameter and they cannot
be declared as optional.
using System;
class Program
{
public static void Main()
{
int res = Add(10, 2);
int[] mar = { 1, 2, 3, 4 };
res = Add(mar);
Console.WriteLine(res.ToString());
res = Add();
res = Add(1, 2, 3, 4, 5);
res = Add(1, 2, 3, 4, 5, 6);
res = Add(1, 2, 3, 4, 5, 6, 7);
Console.WriteLine(res.ToString());
}
2
Deccansoft Software Language Chapter-
Fig: 3.11
Fig: 3.13
2
Deccansoft Software Language Chapter-
The argument “n2” is passed by reference to “b”, i.e. both “b” and “n2” reference to same memory and
hence change made to “b” is also reflected in “n2”.
Out parameter must be initialized in the method and are generally used in situations where we want to
return more than one value from the method.
If a method has return type anything other than “void”, all code paths in it must return a value.
The example below compilation error because if a==0 nothing is mentioned as return value:
Summary
In this section we have covered most of the C# language structures that includes: Datatypes declaration &
initialization, conditional and looping structures, working with arrays & methods and enumerated datatypes.