Post on 10-Apr-2018
transcript
8/8/2019 c#.Net Assignment
1/27
C#.NET
ASSIGNMENT
NIKITA PRABHU 4NM07IS038
NAGARAJA BALLAL 4NM07IS034
MANJUNATH.B.JULPI 4NM07IS031
8/8/2019 c#.Net Assignment
2/27
33)Explain with examples all parameter passing mechanisms in c#?
Methods (static &instance level) tend to take parameters passed in by the caller.
C# provides a set of parameter modifires that control how arguments are sent into agiven method
Parameter modifier Meaning
(none) If a parameter is not marked with a
parameter modifier, it is assumed to be
passed by value, meaning the called
method receives a copy of the original
data
out Output parameters must be assigned by
the method being called (and therefore
are passed by reference). If the called
method fails to assign output parameters,
you are issued a compiler error.
Ref The value is initially assigned by the caller
and may be optionally reassigned by the
called method (as the data is also passed
by reference). No compiler error is
generated if the called method fails toassign a ref parameter
params This parameter modifier allows you to
send in a variable number of arguments
as a single logical parameter. A method
can have only a single params modifier,
and it must be the final parameter of the
method.
The Default Parameter-Passing Behavior
The default manner in which a parameter is sent into a function is by value. Simply put, if
you do not mark an argument with a parameter-centric modifier, a copy of the data is passed
into the function.
// Arguments are passed by value by default.
static int Add(int x, int y)
{
8/8/2019 c#.Net Assignment
3/27
int ans = x + y;
// Caller will not see these changes
// as you are modifying a copy of the
// original data.
x = 10000; y = 88888;
return ans;
}
Here the incoming integer parameters will be passed by value.
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
// Pass two variables in by value.
int x = 9, y = 10;
Console.WriteLine("Before call: X: {0}, Y: {1}", x, y);
Console.WriteLine("Answer is: {0}", Add(x, y));
Console.WriteLine("After call: X: {0}, Y: {1}", x, y);
Console.ReadLine();
}
The values of x and y remain identical before and after the call add().
The out Modifier
Methods that have been defined to take output parameters (via the out keyword) are under
obligation to assign them to an appropriate value before
exiting the method.
An example:
// Output parameters must be assigned by the member
staticvoidAdd(int x, int y, out int ans)
8/8/2019 c#.Net Assignment
4/27
{
ans = x + y;
}
Calling a method with output parameters also requires the use of the out modifier. Recallthat local variables passed as output variables are not required to be assigned before use (if
you do so,the original value is lost after the call),
for example:
static void Main(string[] args)
{
// No need to assign initial value to local variables
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0}", ans);
}
c# allows the caller to obtain multiple return values from a single method invocation.
// Returning multiple output parameters.
static void FillTheseValues(out int a, out string b, outbool c)
{
a = 9;
b = "Enjoy your string.";
c = true;
}
The caller would be able to invoke the following method:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
...
int i; string str; bool b;
FillTheseValues(out i, out str, outb);
8/8/2019 c#.Net Assignment
5/27
Console.WriteLine("Int is: {0}", i);
Console.WriteLine("String is: {0}", str);
Console.WriteLine("Boolean is: {0}", b);
Console.ReadLine();
}
Ref modifier
Reference parameters are necessary when you wish to allow a method to operate on (and
usually change the values of) various data points declared in the callers scope (such as asorting or swapping routine).
AN EXAMPLE:
// Reference parameters.
public static void SwapStrings(ref string s1, ref string s2)
{
string tempStr = s1;
s1 = s2;
s2 = tempStr;
}
This method can be called as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
...
string s1 = "Flip";
string s2 = "Flop";
Console.WriteLine("Before: {0}, {1} ", s1, s2);
SwapStrings(ref s1, ref s2);
8/8/2019 c#.Net Assignment
6/27
Console.WriteLine("After: {0}, {1} ", s1, s2);
Console.ReadLine();
}
output vs reference parameters:
Output parameters do not need to be initialized before they passed to the method.
The method must assign output parameters before exiting.
Reference parameters must be initialized before they are passed to the method.You are passing a reference to an existing variable. If you dont assign it to an initialvalue,
that would be the equivalent of operating on an unassigned local variable.
Params modifier
The params keyword allows you to pass into a method a variable number of parameters (of
the same type) as a single logical parameter. As well, arguments marked with the params
keyword can be processed if the caller sends in a strongly typed array or a comma-delimited
list of items.
If you were to prototype this method to take an array of doubles, this would force the caller to
first define the array, then fill the array, and finally pass it into the method. However, if you
define CalculateAverage() to take a params of integer data types, the caller can simply pass a
commadelimited
list of doubles. The .NET runtime will automatically package the set of doubles into an array
of type double behind the scenes:
// Return average of "some number" of doubles.
static double CalculateAverage(params double[] values)
{
Console.WriteLine("You sent me {0} doubles.", values.Length);
double sum = 0;
if(values.Length == 0)
return sum;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return (sum / values.Length);
}
8/8/2019 c#.Net Assignment
7/27
This method has been defined to take a parameter array of doubles.
The first invocation of this method would result in a compiler
error):
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
...
// Pass in a comma-delimited list of doubles...
double average;
average = CalculateAverage(4.0, 3.2, 5.7, 64.22, 87.2);
Console.WriteLine("Average of data is: {0}", average);
// ...or pass an array of doubles.
double[] data = { 4.0, 3.2, 5.7 };
average = CalculateAverage(data);
Console.WriteLine("Average of data is: {0}", average);
// Average of 0 is 0!
Console.WriteLine("Average of data is: {0}", CalculateAverage());
Console.ReadLine();
}
34) write a function SearchAndRepalce(src,pattern,replace) to replace thepattern string with the replace string in the src string,if found,else leave
src unaltered.Use only System.String memebers
using System;
using System.Collections.Generic;
using System.Text;
8/8/2019 c#.Net Assignment
8/27
namespace search
{
class Program
{
static void SearchAndReplace(string src, string pattern, string replace)
{
if (src.Contains(pattern))
{
src = src.Replace(pattern, replace);
Console.WriteLine(src);
}
else
{
Console.WriteLine("Patern not found");
}
}
static void Main(string[] args)
{
string src, pattern, replace;
Console.WriteLine("enter the Source string:");
src = Console.ReadLine();
Console.WriteLine("enter the Patern string:");
pattern = Console.ReadLine();
Console.WriteLine(" enter the Replace string:");
replace = Console.ReadLine();
SearchAndReplace(src, pattern, replace);
Console.ReadLine();
8/8/2019 c#.Net Assignment
9/27
}
}
}
35) Differentiate between value types and reference types.What is a method
parameter modifier?Explain with code snippets atleast two such modifiers .
The difference between value types and reference types is as follows
QUERIES VALUETYPE REFERNCE TYPE
Where is this type allocated?
How is variable represented?
What is the base type?
Can this type function as a
base to other types?
What is the default
parameter behavior?
Can this type override
System.object.finalize?
Allocated on the stack
Variables are local variables
Must derive from
System.valueType
No .value types are always
sealed & cant be extended
Variables are passed by
value
No.value type are never
placed onto the heap and do
not need to finalized
Allocated on the managed
heap
Variables are pointing to
the memory occupied by
the allocated instance
Must derive from other
type expect
System.ValueType
Yes.if the type is not sealed
,it may fuction as a base to
other types
Variables are passed by
reference
Yes,indirectly
8/8/2019 c#.Net Assignment
10/27
When do variables of this
type die?
When they fall out of the
defining scope
When the managed heap is
garbage collected
METHOD PARAMETER MODIFIER
Methods (static &instance level) tend to take parameters passed in by the caller.
C# provides a set of parameter modifires that control how arguments are sent into agiven method
Parameter modifier Meaning
(none) If a parameter is not marked with a
parameter modifier, it is assumed to be
passed by value, meaning the called
method receives a copy of the original
data
Out Output parameters must be assigned by the
method being called (and therefore are
passed by reference). If the called method
fails to assign output parameters, you are
issued a compiler error.
ref The value is initially assigned by the caller
and may be optionally reassigned by the
called method (as the data is also passed by
reference). No compiler error is generated
if the called method fails to assign a ref
parameter.
The Default Parameter-Passing Behavior
The default manner in which a parameter is sent into a function is by value. Simply put, if
you do not mark an argument with a parameter-centric modifier, a copy of the data is passed
into the function.
// Arguments are passed by value by default.
8/8/2019 c#.Net Assignment
11/27
static int Add(int x, int y)
{
int ans = x + y;
// Caller will not see these changes
// as you are modifying a copy of the
// original data.
x = 10000; y = 88888;
return ans;
}
Here the incoming integer parameters will be passed by value.
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
// Pass two variables in by value.
int x = 9, y = 10;
Console.WriteLine("Before call: X: {0}, Y: {1}", x, y);
Console.WriteLine("Answer is: {0}", Add(x, y));
Console.WriteLine("After call: X: {0}, Y: {1}", x, y);
Console.ReadLine();
}
The values of x and y remain identical before and after the call add().
The out Modifier
Methods that have been defined to take output parameters (via the out keyword) are under
obligation to assign them to an appropriate value before
exiting the method.
An example:
8/8/2019 c#.Net Assignment
12/27
// Output parameters must be assigned by the member
staticvoidAdd(int x, int y, out int ans)
{
ans = x + y;
}
Calling a method with output parameters also requires the use of the out modifier. Recall
that local variables passed as output variables are not required to be assigned before use (if
you do so,the original value is lost after the call),
for example:
static void Main(string[] args)
{
// No need to assign initial value to local variables
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0}", ans);
}
c# allows the caller to obtain multiple return values from a single method invocation.
// Returning multiple output parameters.
static void FillTheseValues(out int a, out string b, outbool c)
{
a = 9;
b = "Enjoy your string.";
c = true;
}
The caller would be able to invoke the following method:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
...
8/8/2019 c#.Net Assignment
13/27
int i; string str; bool b;
FillTheseValues(out i, out str, outb);
Console.WriteLine("Int is: {0}", i);
Console.WriteLine("String is: {0}", str);
Console.WriteLine("Boolean is: {0}", b);
Console.ReadLine();
}
36) what is the difference between System.String and
System.Text:StringBuilder? Explain with relevant code some of features of
string builder class
Main difference between System.String and sytem.Text:StringBuilder is system.string
returns modified copy of the string but do not modify the underlying buffer of existing string
objects whereas string builder provides you direct access to the underlyong buffer.
For example when you call ToUpper() on a string object,you are not modifying the
underlying buffer of an existing object,but receive a new string object in uppercase form
Static void Main(string[] args)
{
System.String str=this is how began life;
Console.WriteLine(str);
String upperversion=str.ToUpper();
Console.WriteLine(str);
Console.WritelINE({0}},UPERVERSION);
}
To reduce the amount of string copying,the System.Text namespace defines a classnamed StringBuilder
Like System.String this also orvides numerous members that allow you toappend,format ,insert data into the object
When you String Builder object ,you may specify the initial no of characters the objectcan contain.If you do not do so the defaultcapacity of a string builder is 6.
8/8/2019 c#.Net Assignment
14/27
using System;
using System.Collections.Generic;
using System.Text;
namespace stringapp
{
class Program
{
static void Main(string[] args)
{
StringBuilder mubuffer = new StringBuilder("my string data");
Console.WriteLine("capacity of this string bulider {0}", mubuffer.Capacity);
mubuffer.Append("contains some numerical data");
mubuffer.AppendFormat("{0},{1}", 44, 99);
Console.WriteLine("capacity of this stringbuilder:{0}", mubuffer.Capacity);
Console.WriteLine(mubuffer);
}
}
}
Output:
Capacity of this Stringbuider:16
Capacity of this Stringbuider:90
Mystring data contains some numerical data:44,99
In many cases Ssytem.String will be your textual object of choice.
If you are building a text-intensive application,you will mosty likely find that
System.Text.StringBuilder improves performance
8/8/2019 c#.Net Assignment
15/27
37) programUsing system;Using system.collections.generic;Using system.text;Namespace consoleapplication1
{Class program{
Static Void Main(String[] args){
double popa=800000000;double popb=1071000000;int yr=0;while(popa
8/8/2019 c#.Net Assignment
16/27
PadLeft() These methods are used to pad a string with somecharacters.PadRight()Remove() Use these methods to receive a copy of a string, with
modifications (charactersReplace() removed or replaced).Split() This method returns a String array containing thesubstrings in this instance thatare delimited by elements of a specified Char or String array.
Trim() This method removes all occurrences of a set of specifiedcharacters from thebeginning and end of the current string.
ToUpper() These methods create a copy of the current string in
uppercase or lowercaseToLower() format, respectively.Basic String ManipulationSimply create a string data type and make use of the providedfunctionality via the dot operator. Do be aware that a few of themembers of System.String are static members, and aretherefore called at the class (rather than theobject) level. Assume you have created a new ConsoleApplication project named FunWithStrings.
Author the following method, which is called from within Main():static void BasicStringFunctionality(){Console.WriteLine("=> Basic String functionality:");string firstName = "Freddy";Console.WriteLine("Value of firstName: {0}", firstName);Console.WriteLine("firstName has {0} characters.",firstName.Length);Console.WriteLine("firstName in uppercase: {0}",firstName.ToUpper());Console.WriteLine("firstName in lowercase: {0}",firstName.ToLower());Console.WriteLine("firstName contains the letter y?: {0}",firstName.Contains("y"));Console.WriteLine("firstName after replace: {0}",firstName.Replace("dy", ""));Console.WriteLine();}Not too much to say here, as this method simply invokes
various members (ToUpper(),
8/8/2019 c#.Net Assignment
17/27
Contains(), etc.) on a local string variable to yield variousformats and transformations. Figure 3-9shows the initial output.string Concatenation
String variables can be connected together to build larger stringtypes via the C# + operator. As youmay know, this technique is formally termed stringconcatenation. Consider the following newhelper function:static void StringConcatenation(){Console.WriteLine("=> String concatenation:");string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";string s3 = s1 + s2;Console.WriteLine(s3);Console.WriteLine();}Also another example
static void StringConcatenation(){
Console.WriteLine("=> String concatenation:");string s1 = "Programming the ";string s2 = "PsychoDrill (PTP)";string s3 = String.Concat(s1, s2);Console.WriteLine(s3);Console.WriteLine();}Escape CharactersLike in other C-based languages, C# string literals may containvarious escape characters, whichqualify how the character data should be printed to the outputstream. Each escape characterbegins with a backslash, followed by a specific token. In caseyou are a bit rusty on the meaningsbehind these escape characters, Table 3-6 lists the morecommon options.\' Inserts a single quote into a string literal.\" Inserts a double quote into a string literal.\\ Inserts a backslash into a string literal. This can be quite
helpful when defining file
8/8/2019 c#.Net Assignment
18/27
paths.\a Triggers a system alert (beep). For console programs, thiscan be an audio clue tothe user.
\n Inserts a new line (on Win32 platforms).\r Inserts a carriage return.\t Inserts a horizontal tab into the string literal.For example, to print a string that contains a tab between eachword, you can make use of the\t escape character. As another example, assume you wish tocreate a string literal that containsquotation marks, another that defines a directory path, and afinal string literal that inserts three
blank lines after printing the character data. To do so withoutcompiler errors, you would need tomake use of the \", \\, and \n escape characters. As well, toannoy any person within a 10 footradius from you, notice that I have embedded an alarm withineach string literal (to trigger a beep).Consider the following:static void EscapeChars(){
Console.WriteLine("=> Escape characters:\a");string strWithTabs = "Model\tColor\tSpeed\tPet Name\a ";Console.WriteLine(strWithTabs);Console.WriteLine("Everyone loves \"Hello World\"\a ");Console.WriteLine("C:\\MyApp\\bin\\Debug\a ");// Adds a total of 4 blank lines (then beep again!).Console.WriteLine("All finished.\n\n\n\a ");Console.WriteLine();}Defining Verbatim StringsWhen you prefix a string literal with the @ symbol, you havecreated what is termed a verbatimstring. Using verbatim strings, you disable the processing of aliterals escape characters and printout a string as is. This can be most useful when working withstrings representing directory andnetwork paths. Therefore, rather than making use of \\ escapecharacters, you can simply write thefollowing:
// The following string is printed verbatim
8/8/2019 c#.Net Assignment
19/27
// thus, all escape characters are displayed.Console.WriteLine(@"C:\MyApp\bin\Debug");Also note that verbatim strings can be used to preserve whitespace for strings that flow over
multiple lines:// White space is preserved with verbatim strings.string myLongString = @"This is a veryveryverylong string";Console.WriteLine(myLongString);Using verbatim strings, you can also directly insert a doublequote into a literal string by
doubling the " token, for example:Console.WriteLine(@"Cerebus said ""Darrr! Pret-ty sun-sets""");Strings Are ImmutableOne of the interesting aspects of System.String is that once youassign a string object with its initialvalue, the character data cannot be changed. At first glance,this might seem like a flat-out lie,given that we are always reassigning strings to new values anddue to the fact that the System.
String type defines a number of methods that appear to modifythe character data in one way oranother (uppercasing, lowercasing, etc.). However, if you lookmore closely at what is happeningbehind the scenes, you will notice the methods of the stringtype are in fact returning you a brandnewstring object in a modified format:static void StringAreImmutable(){// Set initial string value.string s1 = "This is my string.";Console.WriteLine("s1 = {0}", s1);// Uppercase s1?string upperString = s1.ToUpper();Console.WriteLine("upperString = {0}", upperString);// Nope! s1 is in the same format!Console.WriteLine("s1 = {0}", s1);}
The same law of immutability holds true when you use the C#
assignment operator. To illustrate,
8/8/2019 c#.Net Assignment
20/27
comment out (or delete) any existing code withinStringAreImmutable() (to decrease theamount of generated CIL code) and add the following codestatements:
static void StringAreImmutable(){string s2 = "My other string";s2 = "New string value";}
39)The System.Array Base Class
Every array you create gathers much of its functionality from the System.Array class. Using theseCommon members, we are able to operate on an array using a consistentobject model.
Clear ()
Copy To ()
GetEnumerator()
Length
Rank
Reverse ()
Sort ()
this static method sets a range of elements in the array toemptyvalues(0 for value items, static for object references).
this method is used to copy elements from the source array
into thedestination array.
this method returns the IEnumerator interface for a given
array.this interface is required by the foreach construct.
this property returns the number of items within the array
this property returns the number of dimensions of the currentarray.
this static method reverses the contents of a one-dimensionalarray.
this static method sorts a one-dimensional array of intrinsictypes. Ifthe elements in the array implement the IComparer interface,you canalso sort your custom types.
8/8/2019 c#.Net Assignment
21/27
Lets see some of these members in action. The following helper methodmakes use of the staticReverse () and Clear() methods to pump out information about an array ofstring types to theConsole:
Static void SystemArrayFunctionality (){Console.WriteLine ("=> Working with System. Array.");// Initialize items at startup.string [] gothicBands = {"Tones on Tail", "Bauhaus", "Sisters of Mercy"};// Print out names in declared order.Console.WriteLine (" -> Here is the array:");for (int i = 0; i
8/8/2019 c#.Net Assignment
22/27
Value types Reference types
Allocated on the stack Allocated on the managed heap
Value type variables are local copies Reference type variables are
pointing to the memory occupied by
the allocated instance.
Must derive from System.ValueType. Can derive from any other type
(except System.ValueType), as long
as that type is not sealed
Value types are always sealed and
cannot be extended.
If the type not sealed, it may
function as a base to other types.
Variables are passed by value (i.e., a
copy of the variable is passed into
the called function.)
Variables are passed by
reference(i.e., the address of the
variable is passed into the called
function)
Value types are never placed onto
the heap and therefore do not need
to be finalized.
Indirectly they can override
system.object.finalize
Constructors can be defined but thedefault constructor is reserved.
We can define the constructors ofthis type.
These type variables die when they fall out of variables of this typedie when the object is garbage collected.the defining Scope
.
41. EXPLAIN THE CORE MEMBERS OF THE SYSTEM.OBJECT CLASS
Core Members ofSystem. Object
Equals ()
By default, this method returns true only if the items being compared refer to the exact
same item in memory. Thus, Equals () is used to compare object references, not the
state of the object.
This method is overridden to return true only if the objects being compared have the
same internal state values (that is, value-based semantics).
If you override Equals (), you should also override GetHashCode (), as these methods
are used internally by Hash table types to retrieve Sub objects from the container.
8/8/2019 c#.Net Assignment
23/27
GetHashCode ()
This method returns an int that identifies a specific object instance.
GetType ()
This method returns a Type object that fully describes the object you are currently
referencing. In short, this is a Runtime Type Identification (RTTI) method available to all objects
ToString ()
This method returns a string representation of this object, using the
. format (termed thefully qualifiedname).
This method can be overridden by a subclass to return a tokenized string of
name/value pairs that represent the objects internal state, rather than its fully qualified
name.
Finalize()
This method (when overridden) is called to free any allocated resources before theObject is destroyed.
MemberwiseClone ()
This method exists to return a member-by-member copy of the current object, which
is often used when cloning an object.
Illustrate the default behavior of System.Object base class
Class Person
{
Static void Main(string[] args)
{
Console.WriteLine("***** Fun with System.Object *****\n");
Person p1 = new Person();
Console.WriteLine("ToString: {0}", p1.ToString());
Console.WriteLine("Hash code: {0}", p1.GetHashCode());
Console.WriteLine("Base Type: {0}", p1.GetType().BaseType);
// Make some other references to p1.
Person p2 = p1;
Object o = p2;
// Are the references pointing to the same object in memory?if (o.Equals(p1) && p2.Equals(o))
{
Console.WriteLine("Same instance!");
}
Console.ReadLine();
}
}
The Output:
*****Fun with System.Object *****
ToString: consoleapplication4.Person
Hash code:64523424Type:System.Object
8/8/2019 c#.Net Assignment
24/27
Same instance!
Overriding some default behaviors of System.Object
Overriding is the process of redefining the behavior of an inherited virtual member in
a derived class.
As you have just seen, System.Object defines a number of virtual methods( such asToString (),Equals (),GetHashCode () ). These methods are overridden in the derived
class, using override keyword.
42. EXPLAIN SYSTEM DATA TYPES AND C# ALIASES.
SYSTEM DATA TYPES
C# defines an intrinsic set of data types, which are used to represent local variables,
member variables, return values, and input parameters.
These keywords are much more than simple compiler-recognized tokens. Rather, the
C# data type keywords are actually shorthand notations for full-blown types in theSystem namespace.
The Intrinsic Data Types of C#
CLS C# Shorthand Compliant? System Type Range Meaning in Life
bool Yes System.Boolean True or false Represents truth or
falsity
sbyte No System.SByte 128 to 127 Signed 8-bit number
byte Yes System.Byte 0 to 255 Unsigned 8-bit number
Comparing two intrinsic data types for equalitySystem.Int32 a=1000; // same as int a=1000
C# ALIASES
The C# using keyword can also be used to create an alias to a types fully qualified
name. When you do so, you are able to define a token that is substituted with the
types full name at compile time.
For example:
using System;
using MyShapes;
using My3DShapes;// Resolve the ambiguity using a custom alias.
using The3DHexagon = My3DShapes.Hexagon;
namespace MyApp
{
class ShapeTester
{
static void Main(string[] args)
{
// This is really creating a My3DShapes.Hexagon type.
The3DHexagon h2 = new The3DHexagon();
...}
8/8/2019 c#.Net Assignment
25/27
}
}
This alternative using syntax can also be used to create an alias to a lengthy
namespace.
For example:
using MyAlias = System.Runtime.Serialization.Formatters.Binary;namespace MyApp
{
class ShapeTester
{
static void Main(string[] args)
{
MyAlias.BinaryFormatter b = new MyAlias.BinaryFormatter();
}
}
}
43. EXPLAIN THE C# ITERATION CONSTRUCTS WITH EXAMPLE.
C# provides the following four iteration constructs:
for loop
foreach/in loop
while loop
do/while loop
THE FOR LOOP
When you need to iterate over a block of code a fixed number of times, the for
statement provides a good deal of flexibility. You are able to specify how
many times a block of code repeats itself, as well as the terminating condition.
For example:
// A basic for loop.
static void ForAndForEachLoop()
{
// Note! "i" is only visible within the scope of the for loop.
for(int i = 0; i < 4; i++)
{Console.WriteLine("Number is: {0} ", i);
}
// "i" is not visible here.
}
All of your old C, C++, and Java tricks still hold when building a C# for
statement. You can create complex terminating conditions, build endless
loops, and make use of the goto, continue, and break keywords.
THE FOREACH LOOP
The C# foreach keyword allows you to iterate over all items within an array,without the need to test for the arrays upper limit.
8/8/2019 c#.Net Assignment
26/27
For example:
// Iterate array items using foreach.
static void ForAndForEachLoop()
{
...
string[] carTypes = {"Ford", "BMW", "Yugo", "Honda" };foreach (string c in carTypes)
Console.WriteLine(c);
int[] myInts = { 10, 20, 30, 40 };
foreach (int i in myInts)
Console.WriteLine(i);
}
In addition to iterating over simple arrays, foreach is also able to iterate over
system-supplied or user-defined collections.
THE WHILE AND DO/WHILE LOOPING CONSTRUCTS
The while looping construct is useful when you wish to execute a block ofstatements until some terminating condition has been reached. Within the
scope of a while loop, you will, need to ensure terminating event is indeed
established; otherwise, it will be stuck in an endless loop.
In the following example, the message In while loop will be continuously
printed until the user terminates the loop by entering yes at the command
prompt:
static void ExecuteWhileLoop()
{
string userIsDone = "";
// Test on a lower-class copy of the string.while(userIsDone.ToLower() != "yes")
{
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
Console.WriteLine("In while loop");
}
}
Like a simple while loop, do/while is used when you need to perform some action an
undetermined number of times. The difference is that do/while loops are guaranteed to
execute the corresponding block of code at least once (in contrast, it is possible that a
simple while loop may never execute if the terminating condition is false from theonset).
For example:
static void ExecuteDoWhileLoop()
{
string userIsDone = "";
do
{
Console.WriteLine("In do/while loop");
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
}while(userIsDone.ToLower() != "yes"); // Note the semicolon!}
8/8/2019 c#.Net Assignment
27/27
44. EXPLAIN THE ACCESSIBILITY KEYWORDS OF C#.
Types (classes, interfaces, structures, enumerations, delegates) and their members
(properties, methods, constructors, fields, and so forth) are always defined using a
specific keyword to control how visible the item is to other parts of yourapplication.
C# Access Modifier Meaning in Life
public Public items have no access restrictions. A public member can
be accessed from an object as well as any derived class.
A public type can be accessed from other external assemblies.
private Private items can only be accessed by the class (or structure)
that defines the item.
protected Protected items are not directly accessible from an object
variable; however, they are accessible by the defining type as
well as by derived classes.internal Internal items are accessible only within the current assembly.
Therefore, if you define a set of internal types within a .NET
class library, other assemblies are not able to make use of them.
protected internal When the protected and internal keywords are combined on an
item, the item is accessible within the defining assembly, the
defining class, and by derived classes.
For establishing type visibility, there are two keywords used which are:
Public
Internal
By default, internal is the accessibility for types in c#.