Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
155 views

Assignment: Nikita Prabhu 4NM07IS038 Nagaraja Ballal 4NM07IS034 Manjunath.B.Julpi 4Nm07Is031

The document discusses parameter passing mechanisms in C#. It explains that by default, parameters are passed by value where the called method receives a copy of the original data. It then describes three parameter modifiers: 1) out - Output parameters must be assigned by the called method and are passed by reference. The caller can obtain multiple return values from a single method call using out parameters. 2) ref - Reference parameters allow a method to modify data declared in the caller's scope and are passed by reference. The referenced variables must be initialized before passing to the method. 3) params - Allows passing a variable number of arguments as a single logical parameter. The arguments must be of the same type and can be processed as

Uploaded by

nagaraja_ballal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views

Assignment: Nikita Prabhu 4NM07IS038 Nagaraja Ballal 4NM07IS034 Manjunath.B.Julpi 4Nm07Is031

The document discusses parameter passing mechanisms in C#. It explains that by default, parameters are passed by value where the called method receives a copy of the original data. It then describes three parameter modifiers: 1) out - Output parameters must be assigned by the called method and are passed by reference. The caller can obtain multiple return values from a single method call using out parameters. 2) ref - Reference parameters allow a method to modify data declared in the caller's scope and are passed by reference. The referenced variables must be initialized before passing to the method. 3) params - Allows passing a variable number of arguments as a single logical parameter. The arguments must be of the same type and can be processed as

Uploaded by

nagaraja_ballal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

C#.

NET
ASSIGNMENT

NIKITA PRABHU 4NM07IS038

NAGARAJA BALLAL 4NM07IS034

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

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

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)

{
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

static void Add(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, out bool 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, out b);

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 caller’s scope (such as a
sorting 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);

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 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:

// 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);


}

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 the


‘pattern ‘ 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;
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();

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? Allocated on the stack Allocated on the managed
heap

How is variable represented?


Variables are pointing to
Variables are local variables the memory occupied by
the allocated instance

What is the base type?


Must derive from other
Must derive from
type expect
System.valueType
System.ValueType

Can this type function as a Yes.if the type is not sealed


base to other types? No .value types are always ,it may fuction as a base to
sealed & can’t be extended other types

Variables are passed by


What is the default reference
parameter behavior? Variables are passed by
value

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

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 a
given 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.

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:

// Output parameters must be assigned by the member

static void Add(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, out bool 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, out b);

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 class


named StringBuilder
 Like System.String this also orvides numerous members that allow you to
append,format ,insert data into the object
 When you String Builder object ,you may specify the initial no of characters the object
can contain.If you do not do so the defaultcapacity of a string builder is 6.

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

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

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 Characters
Like in other C-based languages, C# string literals may contain various escape
characters, which
qualify how the character data should be printed to the output stream. Each
escape character
begins with a backslash, followed by a specific token. In case you are a bit rusty
on the meanings
behind these escape characters, Table 3-6 lists the more common 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
paths.
\a Triggers a system alert (beep). For console programs, this can be an audio
clue to
the 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 each word, you can
make use of the
\t escape character. As another example, assume you wish to create a string
literal that contains
quotation marks, another that defines a directory path, and a final string literal
that inserts three
blank lines after printing the character data. To do so without compiler errors,
you would need to
make use of the \", \\, and \n escape characters. As well, to annoy any person
within a 10 foot
radius from you, notice that I have embedded an alarm within each 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 Strings
When you prefix a string literal with the @ symbol, you have created what is
termed a verbatim
string. Using verbatim strings, you disable the processing of a literal’s escape
characters and print
out a string as is. This can be most useful when working with strings
representing directory and
network paths. Therefore, rather than making use of \\ escape characters, you
can simply write the
following:
// The following string is printed verbatim
// thus, all escape characters are displayed.
Console.WriteLine(@"C:\MyApp\bin\Debug");
Also note that verbatim strings can be used to preserve white space for strings
that flow over
multiple lines:
// White space is preserved with verbatim strings.
string myLongString = @"This is a very
very
very
long string";
Console.WriteLine(myLongString);
Using verbatim strings, you can also directly insert a double quote into a literal
string by
doubling the " token, for example:
Console.WriteLine(@"Cerebus said ""Darrr! Pret-ty sun-sets""");
Strings Are Immutable
One of the interesting aspects of System.String is that once you assign a string
object with its initial
value, 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 and due to the fact
that the System.
String type defines a number of methods that appear to modify the character
data in one way or
another (uppercasing, lowercasing, etc.). However, if you look more closely at
what is happening
behind the scenes, you will notice the methods of the string type are in fact
returning you a brandnew
string 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,
comment out (or delete) any existing code within StringAreImmutable() (to
decrease the
amount of generated CIL code) and add the following code statements:
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
these
Common members, we are able to operate on an array using a consistent object model.
Clear () this static method sets a range of elements in the array to empty
values
(0 for value items, static for object references).

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.

40. Difference between value type and references type.

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 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

41. EXPLAIN THE CORE MEMBERS OF THE SYSTEM.OBJECT CLASS

Core Members of System. 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.

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!

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 as
ToString (),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 the
System 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 equality


System.Int32 a=1000; // same as int a=1000

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();
}
}
}

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 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.

 THE WHILE AND DO/WHILE LOOPING CONSTRUCTS


 The while looping construct is useful when you wish to execute a block of
statements 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 the
onset).
 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!
}

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 your
application.
 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#.

You might also like