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

(C#) Chapter - 4

C# is a component oriented language that enables one-stop programming. Key features include garbage collection to prevent memory leaks, exceptions for robust error handling, and type safety to prevent issues like uninitialized variables. Variables in C# can be declared with modifiers like static, constant, and volatile to control how they are accessed and their lifetime. Variables are also defined by their data type, scope, accessibility, and lifetime.

Uploaded by

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

(C#) Chapter - 4

C# is a component oriented language that enables one-stop programming. Key features include garbage collection to prevent memory leaks, exceptions for robust error handling, and type safety to prevent issues like uninitialized variables. Variables in C# can be declared with modifiers like static, constant, and volatile to control how they are accessed and their lifetime. Variables are also defined by their data type, scope, accessibility, and lifetime.

Uploaded by

thwe thwe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

C# :A component oriented language

C# is the first “component oriented” language in the


C/C++ family

Component concepts are first class:


Properties, methods, events
Design-time and run-time attributes
Integrated documentation using XML

Enables one-stop programming


No header files, IDL, etc.
Can be embedded in web pages
Goal of C#
Garbage collection
No memory leaks and stray pointers

Exceptions
Error handling is not an afterthought

Type-safety
No uninitialized variables, unsafe casts

Versioning
Pervasive versioning considerations in all aspects of language
design
VARIABLES/IDENTIFIER
 is a program element that stores a value. Some of the values might
contain
 Number
 String
 Character
 Data
 Object

 Four factors determines variable‟s behavior.


1. Data Types – determines the kind of data.
2. Scope – defines the code that can access the variable.
3. Accessibility – determines what code in other module can
access the variable.
4. Lifetime – determine how long the variable‟s value is valid.

 Note : Visibility is a concept that combines Scope, Accessibility and


Lifetime.
string / object
 Fixed length
 Store on the stack

Variable length
Store on the heap
VARIABLE‟S DECLARATION
1. datatype variablename;
int num;

2. datatype variablename = value;


int num = 10;

3. <Accessibility> datatype variablename =value;


public int num = 10;

4. < Accessibility > <const | readonly | static | volatile | static


volatile> datatype variablename =value;
public const int num=100;

Note: If user didn’t use Accessibility during declaring variable, the


system remark this variable as private.
Accessibility
Form Meaning
public Access is not limited.
protected Access is limited to the containing class or
types derived from the containing class.

internal Access is limited to the current assembly.


protected Access is limited to the current assembly or
internal types derived from the containing class.

private Access is limited to the containing type.


Static, Constant, and Volatile
Variables
• The const keyword indicates the value cannot be changed
after it is created.
• The readonly keyword makes the variable similar to a
constant except its value can be set in its declaration or in a
class constructor.
• The static keyword indicates the variable is shared by all
instances of the class.
• The volatile keyword indicates the variable might be
modified by code running in multiple threads running at the
same time.
VARIABLE‟S NAME

A variable‟s name must be a valid C# identifier. It should


begin with a letter, underscore, or @ symbol.

After that, it can include letters, numbers, or underscores. If


the name begins with @, it must include at least one other
character.

Variable names cannot contain special characters such as &,


%, #, and $. They also cannot be the same as C# keywords
such as if, for, and public.
VARIABLE‟S NAME LIST
NAME VALId?
numEmployees Valid
NumEmployees Valid
num_employees Valid
_manager Valid (but unusual)
_ Valid (but confusing)
Invalid (doesn‟t begin with a letter,
1st_employee under-score, or @ symbol)
Invalid (contains the special character
#employees #)
return Invalid (keyword)
VARIABLES‟S VALUES
DataType Default Value
All integer types 0
char type „\x000‟
float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference types null
var DATA TYPE

• The var datatype is like a special data type that makes


Visual Studio determine the data type that a variable
should have based on the value that it is assigned.

var numTypes = 13;


string/String DATA TYPE
the string type is immutable, i.e.,
once it has been created, a string cannot be changed
No characters can be added or removed from it, nor
can its length be changed.

a string's contents have been changed, what has


really happened is that a new string instance has
been created.

cannot be edited but it can be assigned.


string st=“hello”;
string st1 = st;
Constructing Strings
 A predefined reference type

 Declaration

string st1;
String st2;

"string" is a keyword and can't be used "string" as an


variable name. Alias System.String class.
Verbatim Strings - Verbatim string literals begin with
@" and end with the matching quote. They do not have
escape sequences.
 create variables name
 @if, @string

 string st1=@”\EBG\CSharp\my.cs”; (OR)


string st1=“\\EBG\\CSharp\\my.cs”;

a single string to span more than one line


string str =
@"I'm so happy to be a string
that is split across
a number of different
lines.";
Arrays
 Arrays are a data type that are used to represent a large
number of homogeneous values, that is values that are all of
the one data type.

Arrays hold a fixed number of equally sized data elements,


generally of the same data type.

The elements in the Array are always stored in consecutive


memory locations.
One-dimensional Array
Multi-dimensional Array
1. Rectangular
2. Jagged-array
One-dimensional Array
int [ ] num=new int[3]; num [0] = 3;
int [ ] num= new int[] {3,4,5}; num [1] = 4;
int [ ] num={3,4,5}; num [2] = 5;
Person[ ] customers =
{
new Person( ) { FirstName="Ann", LastName="Archer"},
new Person( ) { FirstName="Ben", LastName="Blather"},
new Person( ) { FirstName="Cindy", LastName="Carver"}
};
Multi-dimensional Array
Rectangular num [0,0] = 3;
int[,] num = new int [2,3]; num [0,1] = 4;
num [0,2] = 5;
int[,] num ={{3,4,5},{6,4}};
num [1,0] = 6;
num [1,1] = 4;
Jagged-array num [1,2] = 5;
int[][] a =new int[2][];
a[0] = new int[]{3,4,5};
a[1] = new int[]{5,6,7,8};
Multi-dimensional Array
Jagged-array
int[][] a =new int[2][];
a[0] = new int[3];
a[1] = new int[4];

a[0][0]=3; a[1][0]=5;
a[0][1]=4; a[1][1]=6;
a[0][2]=5; a[1][2]=7;
a[1][3]=8;
Case-sensitive

White space means nothing

 Semicolons (;) to terminate statements

 Code blocks use curly braces ({})

 C++/Java style comments


// or /* */
Also adds /// for automatic XML documentation

Keywords cannot be used as identifiers except when they are


prefixed with the „@‟ character.
Literals
Value constants assigned to variables or results of
expressions

Numeric Literals

Boolean Literals

Character Literals
C#‟s Numeric literal lists
Character Data Type

U unit
L long
UL / LU ulong
F float
D double
M decimal

 For example, 1.23f and 1.23F both give a float result.


Integer Literals

Integers – decimal(100) and hexadecimal


In hexadecimal, 0x or 0X is preceded.
0x64, 0X64

Example:
int hex = 0x64;
Console.WriteLine("{0:x}",hex);
Console.WriteLine(“Hexa value is“ + hex);
Output:
100
Hexa value is 100
Boolean Literals

 2 values
 true and false

Example:
bool flag = false;
Console.WriteLine(flag);
Single Character Literals &
String Literals

„2‟ ( Single character literals )


“2000019” ( String literals )

Example:
char grade=„A‟;
string result=“Credit”;
Backslash Character Literals
\a - Alert (usually the HW beep)
\b - Backspace
\n - New line
\0 - Null
\t - Horizontal tab
\v - Vertical tab
\' - Single quote
\" - Double quote
\\ - Backslash
\f - Form feed
\r - Carriage return
 Casting
A cast operator explicitly tells a program
to convert a value from one type to another type
to convert from object to another object
to convert value type to object and then object to value type
vice visa.

Example:
float num = 10.5f;
int number = (int) num;

Console.Writeline(“{0,m}”,number);
Console.Writeline(“number value is” + number);
Console.Writeline(number.ToString());
Output:
10
number value is 10
10
Casting Object to Another Object
Person personA = new Student();
Student student;
student = (Student)personA;

Casting Value type to Object – Implicit Conversion


int num=100;
Person personA = num;

Casting Object to Value type – Explicit Conversion


int num=100;
Person personA = num;
int result = (int) personA;
Casting Array
• Make an array of Students.
Student[] students = new Student[10];

• Implicit cast to an array of Persons. (A Student is a


type of Person.)
Person[] persons = students;

• Explicit cast back to an array of Students.


students = (Student[])persons;
Parsing
Each of the fundamental data types (except for
string) has a Parse/TryParse method that tries
to convert a string into that type.

string text = "112358";


int value = int.Parse(text);
(OR)
string text = "112358“;
int value;
int.TryParse(text, out value);
(OR)
int value=Convert.ToInt32(“112358”);
Parsing
To convert the numerical value into a string using
ToString method.

int totalcost = 10000;


String/string cost = totalcost.ToString( );
Console.WriteLine(cost);

(OR)

int totalcost = 10000;


Console.WriteLine(totalcost.ToString( ));
SCOPE
A variable‟s scope determines which other pieces of
code can access it. For example, if you declare a
variable inside a method, only code within that
method can access the variable.

The three possible levels of scope are (in increasing


size of scope) block, method, and class.
BLOCK SCOPE
• A block is a series of statements enclosed in braces. If you
declare a variable within a block of code, the variable has
block scope, and only other code within that block can
access the variable.
for (int i = 1; i <= 5; i++) else
{ {
int j = 3; int product = i * j;
if (i == j) Console.WriteLine("Product: "
{ + product);
int sum = i + j; }
Console.WriteLine("Sum: " + int k = 123;
sum); Console.WriteLine("k: " +
} k);
}
METHOD SCOPE
• If you declare a variable inside a method but not within a
block, the variable is visible to any code inside the
procedure that follows the declaration. The variable is not
visible outside of the method.

public void AddOrderItem(Order order, OrderItem item)


{
order.OrderItems.Add(item);
}
CLASS SCOPE
• A variable with class (or structure) scope is available to all
code in its class (or structure) even if the code appears
before the variable‟s declaration.
• Depending on its accessibility keyword, the variable may be
visible outside of the class. For example, if you declare the
variable with the public keyword, it is visible to all code
outside of the class.
public class Lender
{
public void DisplayLoanAmount()
{
MessageBox.Show(LoanAmount.ToString());
}
private decimal LoanAmount;
...
}
PARAMETER DECLARATION
• A parameter declaration for a method defines the names and
types of the parameters passed into it.

• Parameters always have method scope. C# creates


parameter variables when a method begins and destroys
them when the method ends. The method‟s code can access
the parameters, but code outside of the method cannot.

• There are three ways you can pass values into a method: by
value, by reference, and for output.
Pass By Value
By default a parameter‟s value is passed into the method by value. That
means the method receives a copy of the parameter‟s value. If the
method modifies the parameter, it modifies only the copy, so the value
in the calling code remains unchanged.
private void DoubleTest( )
{
int value = 10;
DoubleIt(value);
Console.WriteLine("DoubleTest: " + value.ToString());
}
Output:
private void DoubleIt(int number) DoubleIt: 20
{ DoDouble: 10
number *= 2;
Console.WriteLine("DoubleIt: " + number.ToString());
}
Pass By Reference
One alternative to passing a value into a method by value is to
pass it by reference. In that case the method receives a reference
to the argument‟s value, not a copy of the value. That means if
the method changes the parameter, the argument in the calling
code is also changed.
Output:
private void DoubleTest() DoubleIt: 20
{ DoDouble: 20
int value = 10;
DoubleIt(ref value);
Console.WriteLine("DoubleTest: " + value.ToString());
}

private void DoubleIt(ref int number)


{
number *= 2;
Console.WriteLine("DoubleIt: " + number.ToString());
}
For Output
• The final way you can pass a value into a method uses the out
keyword. This keyword means the parameter is intended to be an
output parameter. The argument is passed into the method by
reference so the method can set its value. The method does not assume
the value has been initialized before it is passed into the method, and
the method assigns a value to the parameter before it returns.
Class Myclass
{
Public void myFun(out int num)
{ public static void Main()
{
num = 100;
int k;
} Myclass obj=new Myclass();
} obj.myFun(out k);
Console.WriteLine(k.ToString());
}
Properties
• In C# a property is similar to a field in a class except it is
implemented by accessor methods instead of as a simple
variable.
• A property‟s get and set accessors allow the program to get
and set the property‟s value.

class Employee public static void Main( )


{ {
private string name; Employee emp = new Employee( );
public string Name emp.Name = "Rod Stephens";
{ Console.WriteLine(emp.Name);
get {return name;} }
set { name = value;}
}
}
 Loop Statements
- while
- do-while
- for
- foreach
 Jump Statements
- break
- continue
- goto
- return
 Selection Statements
- if - else
- switch - default
SYNTAX
using System;

namespace <project name>


{
<Accessibility > class <class name>
{
1. <Accessibility> datatype variablename=value;
2. Properties
3. Method

public static void Main()


{
[statements]
}
}
}
Enumeration
An enumeration (also called an enumerated type or simply
an enum) is a discrete list of specific values called
enumerators. You define the enumeration and the values
allowed. Later, you can declare a variable of the
enumeration‟s type so it can take only those values.

General form:
<Accessibility> enum enumeration_name
{enumeration list};
Enumeration
 General form
enum Color {Red,Green,Blue};
 By default, it starts with 0; can be changed to any number.
enum Color{Red = 10, Green, Blue}
 By default, it increments by 1 for each subsequent name.
 You can sign a value to each name.
enum Color{ Red = 10, Green = 20, Blue = 21}
 You can increment a enum variable.
 Color mycolor;
 mycolor = Color.Green;
 mycolor += 1;
 Console.WriteLine(mycolor); // Blue
 Integer casting must be explicit
Color background = (Color)2;
int oldColor = (int)background;
Operations on Enumeration
 Compare
if (c == Color.red) ...if (c > Color.red && c <=
Color.green) ...
 +, -
c = c + 2;
 ++, --
c++;
&
if ((c & Color.red) == 0) ...
|
c = c | Color.blue;
~
c = ~ Color.red;
Enumeration : Example
using System;
namespace myClass{
class EnumDemo {
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland,McIntosh};
public static void Main()
{
string[] color = { "Red", "Yellow", "Purple", "Orange", "Greeen","lightgreen" };
Apple i;
for( i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(i + " has value of " + i);
for( i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(i + " has value of " + (int)i);
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine("Color of " + i + " is " + color[(int)i]);
Console.ReadLine();
} }}
Enumeration : Example
NULLABLE TYPE
• Most relational databases have a concept of a null data
value. A null value indicates that a field does not contain
any data.
• For example, a null bank balance would indicate that
there is no known balance, whereas a 0 would indicate
that the balance was 0.
• You can create a nullable variable in C# by adding a
question mark after the variable‟s data type.
int? count;
count = null;
count = 1337;
DELEGATES
• A delegate is a reference type that defines a method
signature
• Delegate are object-oriented, type-safe, and secure
function pointers.
• Can invoke both instance and static method.
• All methods invoked by the same delegate must have the
same parameters and return value.
• The method to call is resolved at runtime, not compile
time
• Effective use of Delegate improves the performance of
application.
How to use Delegates?
• Declaration : type declaration
<Accessibility> delegate return_type delegate_name (parameters);
delegate double MathOp( double x, double y);
• Method definition : methods whose references are encapsulated
into a delegate instance are known as delegate methods or callable
entities.
public static double Multiply(double a, double b)
{ return a*b;}
• Instantiation : a delegate-creation-expression is used to create
instance of a delegate
MathOp mop=new MathOp (Multiply)
• Invocation :
double r1 = mop (3.3,4.4);
delegate string StrMod(string str); public static void Main(string[] args) {
class Delegates { string str;
static string ReplaceSpace(string
st) StrMod strOp = new
StrMod(ReplaceSpace);
{
str = strOp("call ReplaceSpcace");
return st;
Console.WriteLine("Result String: " + str);
}
static string RemoveSpace(string strOp = new StrMod(RemoveSpace);
st) str = strOp("call RemoveSpcace");
{ Console.WriteLine("Result String: " + str);
return st; strOp = new StrMod(Reverse);
} str = strOp("call Reverse");
static string Reverse(string st) Console.WriteLine("Result String: " + str);
{ Console.Read();
return st; }
} }
Sample Program
1. Create one dimensional integer array, arr, with the
length of 13. Each index of array, arr, is inserted integer
values. Then, find and display the peak points. Also
display the original array arr.

2. Write a C# program that accepts characters for two-


dimensional jagged array elements from keyboard and
display the array.
using System; {
using System.Collections.Generic; Console.WriteLine(arr[i] + "is a
using System.Linq; peak points");
}
using System.Text;
using System.Threading.Tasks; }
namespace NO1 j++;
}
{ Console.ReadLine();
class Program for (i = 0; i < arr.Length; i++)
{ {
Console.Write(arr[i] + " ");
static void Main(string[] args) }
{ } } }
int i, j = 2;
int[] arr = new int[] { 3,9,1,4,2,0,9,10,2,5,3,7,0};
for (i = 1; i < arr.Length; i++)
{
if (arr[ i ] > arr[i - 1])
{
if (arr[ j ] < arr [ i ])
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NO2
{
class Program
{
static void Main(string[] args)
{
int i , j;
Console.Write("Enter Number of Outer Column\t");
int col=Convert.ToInt32(Console.ReadLine());
int [][] arr = new int[col][];
Console.WriteLine("\n");
for (i = 0; i < arr.Length; i++)
{
Console.Write("Inner Column for each Outer Column:"+ i +"\t");
arr[i] =new int [Convert.ToInt32(Console.ReadLine())];
}
Console.WriteLine("\n");
for (i = 0; i < arr.Length; i++)
{
for (j = 0; j < arr[i].Length; j++)
{
Console.Write("Enter Value for jadded
array:arr["+i+"]"+"["+j+"]\t");
arr[i][j] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
}
Console.WriteLine("Output Result");
for (i = 0; i < arr.Length; i++)
{
for (j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j]+"\t\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
}

You might also like