Assignment: Nikita Prabhu 4NM07IS038 Nagaraja Ballal 4NM07IS034 Manjunath.B.Julpi 4Nm07Is031
Assignment: Nikita Prabhu 4NM07IS038 Nagaraja Ballal 4NM07IS034 Manjunath.B.Julpi 4Nm07Is031
NET
ASSIGNMENT
MANJUNATH.B.JULPI 4NM07IS031
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 a
given method
data
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.
{
int ans = x + y;
// original data.
x = 10000; y = 88888;
return ans;
int x = 9, y = 10;
Console.ReadLine();
The values of x and y remain identical before and after the call add().
Methods that have been defined to take output parameters (via the out keyword) are under
obligation to assign them to an appropriate value before
An example:
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:
int ans;
c# allows the caller to obtain multiple return values from a single method invocation.
a = 9;
c = true;
...
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 caller’s scope (such as a
sorting or swapping routine).
AN EXAMPLE:
// Reference parameters.
s1 = s2;
s2 = tempStr;
...
string s1 = "Flip";
string s2 = "Flop";
Console.ReadLine();
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 don’t 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:
double sum = 0;
if(values.Length == 0)
return sum;
sum += values[i];
error):
...
double average;
average = CalculateAverage(data);
// Average of 0 is 0!
Console.ReadLine();
using System;
using System.Collections.Generic;
using System.Text;
namespace search
class Program
if (src.Contains(pattern))
Console.WriteLine(src);
else
src = Console.ReadLine();
pattern = Console.ReadLine();
replace = Console.ReadLine();
Where is this type allocated? Allocated on the stack Allocated on the managed
heap
Yes,indirectly
Can this type override
System.object.finalize? No.value type are never
placed onto the heap and do
not need to finalized
When do variables of this When they fall out of the When the managed heap is
type die? defining scope garbage collected
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 a
given method
data
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.
int ans = x + y;
// original data.
x = 10000; y = 88888;
return ans;
int x = 9, y = 10;
Console.ReadLine();
The values of x and y remain identical before and after the call add().
Methods that have been defined to take output parameters (via the out keyword) are under
obligation to assign them to an appropriate value before
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:
int ans;
c# allows the caller to obtain multiple return values from a single method invocation.
a = 9;
c = true;
{
Console.WriteLine("***** Fun with Methods *****");
...
Console.ReadLine();
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
Console.WriteLine(str);
String upperversion=str.ToUpper();
Console.WriteLine(str);
Console.WritelINE(“{0}},UPERVERSION);
using System;
using System.Collections.Generic;
using System.Text;
namespace stringapp
class Program
Console.WriteLine(mubuffer);
Output:
37) program
Using 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<=popb)
{
popa=popa+(popa*2.1/100);
popb=popb+(popb*1.3/100);
yr++;
}
Console.Writeline(“no of year for population of A to exceed that of B:{0},yr);
}
}
}
38)UNDERSTANDING SYSTEM.STRING:
System.String provides a number of methods you would expect from such a
utility class, including
methods that return the length of the character data, find substrings within the
current string,
convert to and from uppercase/lowercase, and so forth. Table 3-5 lists some (but
by no means all) of
the interesting members.
tring Member Meaning in Life
Length This property returns the length of the current string.
Compare() This method compares two strings.
Contains() This method determines whether a string contains a specific
substring.
Equals() This method tests whether two string objects contain identical
character data.
Format() This method formats a string using other primitives (e.g., numerical
data, other
strings) and the {0} notation examined earlier in this chapter.
Insert() This method inserts a string within a given string.
PadLeft() These methods are used to pad a string with some characters.
PadRight()
Remove() Use these methods to receive a copy of a string, with modifications
(characters
Replace() removed or replaced).
Split() This method returns a String array containing the substrings in this
instance that
are delimited by elements of a specified Char or String array.
Trim() This method removes all occurrences of a set of specified characters
from the
beginning and end of the current string.
ToUpper() These methods create a copy of the current string in uppercase or
lowercase
ToLower() format, respectively.
Basic String Manipulation
Simply create a string data type and make use of the provided functionality via
the dot operator. Do be aware that a few of the
members of System.String are static members, and are therefore called at the
class (rather than the
object) level. Assume you have created a new Console Application 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(),
Contains(), etc.) on a local string variable to yield various formats and
transformations. Figure 3-9
shows the initial output.
string Concatenation
String variables can be connected together to build larger string types via the C#
+ operator. As you
may know, this technique is formally termed string concatenation. Consider the
following new
helper 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
Copy To () this method is used to copy elements from the source array into the
destination array.
GetEnumerator()
this method returns the IEnumerator interface for a given array.this interface
is required by the foreach construct.
Length
this property returns the number of items within the array
Rank
this property returns the number of dimensions of the current array.
Reverse ()
this static method reverses the contents of a one-dimensional array.
Sort ()
this static method sorts a one-dimensional array of intrinsic types. If
the elements in the array implement the IComparer interface, you can
also sort your custom types.
Let’s see some of these members in action. The following helper method makes use of the
static
Reverse () and Clear() methods to pump out information about an array of string types to the
Console:
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 <= gothicBands.GetUpperBound(0); i++)
{
// Print a name
Console. Write (gothicBands[i] + " ");
}
Console.WriteLine ("\n");
// Reverse them...
Array. Reverse (gothicBands);
Console.WriteLine (" -> The reversed array");
// ... and print them.
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
{
// Print a name
Console. Write (gothicBands[i] + " ");
}
Console.WriteLine ("\n");
// Clear out all but the final member.
Console.WriteLine (" -> Cleared out all but one...");
Array.Clear (gothicBands, 1, 2);
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
{
// Print a name
Console.Write(gothicBands[i] + " ");
}
Console.WriteLine();
}
Here many members of System.Array are defined as static members and are therefore
called at the class level (for example, the Array.Sort() or Array.Reverse() methods). Methods
such as these are passed in the array you wish to process. Other methods of System.Array
(such as the GetUpperBound() method or Length property) are bound at the object level, and
thus you are able to invoke the member directly on the array.
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 If the type not sealed, it may function as a base
extended. to other types.
Variables are passed by value (i.e., a copy of Variables are passed by reference(i.e., the
the variable is passed into the called function.) address of the variable is passed into the called
function)
Value types are never placed onto the heap and Indirectly they can override
therefore do not need to be finalized. system.object.finalize
Constructors can be defined but the default We can define the constructors of this type.
constructor is reserved.
These type variables die when they fall out of variables of this type die when the object
is garbage collected. the defining Scope
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
<namespace>.<type name> format (termed the fully qualified name).
This method can be overridden by a subclass to return a tokenized string of
name/value pairs that represent the object’s internal state, rather than its fully
qualified name.
Finalize()
This method (when overridden) is called to free any allocated resources before the
Object 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:64523424
Type:System.Object
Same instance!
C# ALIASES
The C# using keyword can also be used to create an alias to a type’s fully qualified
name. When you do so, you are able to define a token that is substituted with the
type’s 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();
...
}
}
}
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();
}
}
}
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 C# foreach keyword allows you to iterate over all items within an array,
without the need to test for the array’s upper limit.
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.