Você está na página 1de 48

Notes By Mrs.

Sunitha Pramod ,East Point College of Engg,Bangalore

Chapter 3: C# Language Fundamentals


C# demands that all program logic is contained within a type definition (class, interface, structure,

enumeration, delegate).Unlike C(++), it is not possible to create global functions or global points of data.

In its simplest form, a C# class can be defined as follows:

The Anatomy of a Simple C# Program:

//C# files end with a *.cs file extension.

using System;
class HelloClass
{
public static int Main(string[] args)
{
Console.WriteLine("Hello world");

return 0;
}
}

Note: Every executable C# application must contain a class defining a Main( ) method, which is
used to signify the entry point of the application.

Variations on the Main ( ) Method

The first of Main( ) is defined to take a single parameter (an array of strings) and return an integer
data type. This is not the only possible form of Main(), however. It is permissible to construct your
application's Main( ) method using any of the following signatures:

//Integer return type, array of strings as argument.


public static int Main(string[] args)
{

// Process command line arguments.


// Make some objects.
//Return a value to the system.

// No return type, no arguments.


public static void Main()
{
// Make some objects.
}

Prep By: Sunitha Pramod Page 1


// Integer return type, no arguments.
public static int Main()
{
// Make some objects.
// Return a value to the system.
}

Processing Command Line Parameters

// command line arguments.

using System;
classHelloClass
{
public static int Main(string[] args)
{
Console.WriteLine("***** Command line args *****");

for(int x = 0; x <args.Length; x++)


Console.WriteLine("Arg: {0} ", args[x]);

Console.WriteLine("Hello World!");
return 0;
}
}

Alternative to the standard for loop C# "foreach" keyword.

// Notice we have no need to check the size of the array when using
//'foreach'.

public static int Main(string[] args)


{
foreach(string s in args)
Console.WriteLine("Arg: {0} ", s);
...
}

OutPut:

Prep By: Sunitha Pramod Page 2


Write a C# program to find sum and avg of two numbers

using System;

class program
{
static void Main(string[] args)
{
string s1, s2;

int n1, n2, sum;


float avg;

Console.WriteLine("Enter the first number");


s1 = Console.ReadLine();

Console.WriteLine("Enter the second number");


s2 = Console.ReadLine();

n1 = int.Parse(s1);
n2 = int.Parse(s2);

sum = n1 + n2;
avg = sum / 2;
Console.WriteLine("sum is {0} and avg is {1}", sum,avg);

Console.ReadLine();
}
}

Output:

Enter the first number


3
Enter the second number
7
sum is 10 and avg is 5

Prep By: Sunitha Pramod Page 3


Defining Classes and Creating Objects:

A class is a definition of a user-defined type (UDT). An object describes a given instance


of a particular class. In C#, the "new" keyword is used to create an object instance.

Thus the following illustrative C# logic is illegal


Using System;
Class HelloClass
{
public static int Main(string[] args)
{
// Error! Use of unassigned local variable! Must use 'new'.
HelloClass c1;
c1.SomeMethod();
return 0;
}
}

To illustrate the proper procedure for class instantiation, observe the following update:
// Make HelloClass types correctly using the C# 'new' keyword.

Using System;
classHelloClass
{
public static int Main(string[] args)
{
// You can declare and create a new object in a single line...
HelloClass c1 = new HelloClass();

// ...or break declaration and creation into two lines.


HelloClass c2;
c2 = new HelloClass();
return 0;
}
}

The "new" keyword is in charge of allocating the correct number of bytes for the specified class
and acquiring sufficient memory from the managed heap.

The Role of Constructors:

Prep By: Sunitha Pramod Page 4


Every C# class is automatically endowed with a default constructor. Like C++ (and Java),
default constructors never take arguments. Beyond allocating a new class instance, the default
constructor ensures that all member data is set to an appropriate default value (this behavior is
true for all constructors).

using System;
class helloclass
{
public string usermessage;

public helloclass()
{
Console.WriteLine("\n\nDefault Constr called");
}

public helloclass(string msg)


{
Console.WriteLine("Parametrized constr called");
usermessage = msg;
}

static int Main(string[] args)


{
helloclass c1 = new helloclass();//default const called.
Console.WriteLine("Value of usermessage:{0}\n\n",c1.usermessage);

helloclass c2;
c2 = new helloclass("testing 1, 2, 3");//para constr called
Console.WriteLine("value of usermessage:{0}", c2.usermessage);

Console.ReadLine();
return 0;
}//end of main
}
Output:
Default Constr called

Value of usermessage:

Parametrizedconstr called

value of usermessage: testing 1, 2, 3

C# constructors are named identical to the class they are constructing, and do not take a

Prep By: Sunitha Pramod Page 5


return value (not even void). On examining the program's output we can see that the default
constructor has indeed assigned the internal state data to the default values (zero), while the
parameterized constructor has assigned the member data to values specified by the object user.

Write a c# program for construtors, static constructors and


destructors:

using System;
class Test2
{
static int i;
static Test2()
{ // a constructor for the entire class called
//once before the first object created
i = 4;
Console.WriteLine("inside static construtor...");
}
public Test2()
{
Console.WriteLine("inside regular construtor... i={0}", i);
}
~Test2()
{ // destructor (hopefully) called for each object
Console.WriteLine("inside destructor");
}

static void Main(string[] args)


{
Console.WriteLine("Test2");
Test2 t1=new Test2();
Test2 t2=new Test2();
Console.ReadLine();
}
}

Output:
inside static construtor...
Test2
inside regular construtor... i=4
inside regular construtor... i=4

Defining an Application Object:

Prep By: Sunitha Pramod Page 6


When you build your C# applications, it becomes quite common to have one type
functioning as the "application object" (the type that defines the Main( ) entry point) and
numerous other types that constitute the application at large. On the other hand, it is permissible
to create an application object that defines any number of members called from the type's Main( )
method.
using System;
class helloclass
{
public string usermessage;

public helloclass()
{
Console.WriteLine("\n\nDefault Constr called");
}
public helloclass(string msg)
{
Console.WriteLine("Parametrized constr called");
usermessage = msg;
}
public void printmessage()
{
Console.WriteLine("message is {0}", usermessage);
}
}//end of helloclass
Class helloapp
{
staticint Main(string[] args)
{
helloclass c1 = new helloclass("Hey there........." );
c1.printmessage();
return 0;
}
}
OutPut: Parametrized constr called
message is Hey there........

Basic Input & output with the Console Class:


Many of the example applications make use of the System.Console class. Console is one
of many types defined in the System namespace. As its name implies, this class encapsulates
input, output, and error stream manipulations. Thus, this type is mostly useful when creating
console-based applications rather than Windows based or Web-based applications.

Principal among the methods of System.Console are Read( ), ReadLine( ) Write( ) and
WriteLine( ), all of which are defined as static.

Prep By: Sunitha Pramod Page 7


• WriteLine( ) pumps a text string (including a carriage return) to the output stream.
• The Write( ) method pumps text to the output stream without a carriage return.
• ReadLine( ) allows you to receive information from the input stream up until the carriage
return, while
• Read( ) is used to capture a single character from the input stream.
// Make use of the Console class to perform basic IO.
using System;
class helloclass
{
static int Main(string[] args)
{
Console.Write("\n\nEnter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Name is {0}\n", s);
Console.Write("Enter your age: ");
s = Console.ReadLine();
Console.WriteLine("you are {0} years old: ", s);
Console.ReadLine();

return 0;
}
}

Output:

Enter your name: smith


Name is smith

Enter your age: 25


you are 25 years old:

Formatting Console Output

.NET introduces a new style of string formatting(numerous occurrences of the tokens


{0}, {1} etc), slightly reminiscent of the C printf( ) function, without the cryptic "%d" "%s'" or
"%c" flags.
using System;
classhelloclass
{
static int Main(string[] args)
{
int theInt = 90;
double theDouble = 9.99;
bool theBool = true;
Console.WriteLine(" Int is: {0}\n Double is: {1}\n Bool is : {2}",
theInt, theDouble, theBool);
Console.ReadLine();

Prep By: Sunitha Pramod Page 8


return 0;
}
}

OutPut:
int is: 90
Double is: 9.99
Bool is : True

.NET String Formatting Flags:

If you require more elaborate formatting, each placeholder can optionally contain various
format characters (in either uppercase or lowercase), as seen in the following Table.
C# Format Meaning in life
Character
C or c Used to format currency. By default, the flag will prefix the local cultural
symbol [a dollar sign ($) for US English], however, this can be changed using

D or d Used to format decimal numbers. This flag may also specify the minimum
number of digits used to pad the value.

E or e Exponential notation.

F or f Fixed point formatting


G or g Stands for general. Used to format a number to fixed or exponential format
N or n Basic numerical formatting (with commas).
X or x Hexadecimal formatting. If you use an uppercase X, your hex format will also
contain uppercase character

Example:
using System;

class helloclass
{

static int Main(string[] args)


{
Console.WriteLine("C format: {0:C}", 99989.987);
Console.WriteLine("D7 format: {0:D7}", 99999);
Console.WriteLine("E format: {0:E}", 99999.76453);
Console.WriteLine("F3 format: {0:F3}", 99999.9999);
Console.WriteLine("N format: {0:N}", 99999);
Console.WriteLine("X format: {0:X}", 99999);
Console.WriteLine("x format: {0:x}", 99999);

Console.ReadLine();
return 0;
}
}
Output:

C format: $99,989.99

Prep By: Sunitha Pramod Page 9


D7 format: 0099999
E format: 9.999976E+004
F3 format: 100000.000
N format: 99,999.00
X format: 1869F
x format: 1869f

Establishing Member Visibilty:

using System;
class someclass
{
//Accessible anywhere.
public void publicmethod()
{
Console.WriteLine("Visiblity of member is public");
}

//Accessible from someclass and any derived class


protected void protectedmethod()
{
Console.WriteLine("Visiblity of member is protected");
}

//Accessible only from someclass


private void privatemethod()
{
Console.WriteLine("Visiblity of member is private");
}

//Accessible within same assembly


internal void internalmethod()
{
Console.WriteLine("Visiblity of member is internal");
}

//ASsembly-protected access
protectedinternal void protectedinternalmethod()
{
Console.WriteLine("Visiblity of member is protectedinternal");
}

//Unmarked members are private by default in c#


void somemethod() { }
}

class helloclass
{

static int Main(string[] args)

Prep By: Sunitha Pramod Page 10


{
someclass c = new someclass();
c.publicmethod();
c.internalmethod();
c.protectedinternalmethod();

//c.protectedmethod(); Error
//c.privatemethod(); Error
//c.somemethod(); Error

Console.ReadLine();

return 0;
}
}

Output:
Visiblity of member is public
Visiblity of member is internal
Visiblity of member is protectedinternal

Default values of class member variables:

using System;

class program
{
public int myInt; // set to 0
Public string myString; //set to null
Public bool myBool; // set to false
Public object myObj; //set to null

static void Main(string[] args)


{
program p = new program();
Console.WriteLine("default int value is: {0}\n default string
value is: {1}\n default bool value is: {2}\n default obj value
is: {3}\n", p.myInt, p.myString, p.myBool, p.myObj);
Console.ReadLine();
}
}
Output:
default int value is: 0
default string value is:
default bool value is: False
default obj value is:

Member Variable Initialization Syntax:


Prep By: Sunitha Pramod Page 11
using System;

class program
{
public int myInt=9;
Public string myString="hello";
Public bool myBool=true;
Public object myObj=99.999;

static void Main(string[] args)


{
program p = new program( );
Console.WriteLine("int value is: {0}\n string value is: {1}\n bool value is:
{2}\n obj value is: {3}\n", p.myInt, p.myString, p.myBool, p.myObj);
Console.ReadLine();
}
}

Output:

int value is: 9


string value is: hello
bool value is: True
obj value is: 99.999

Defining Constant Data:


using System;

class ConstData
{
public conststring BestStudentTeam = "7 th ise";
public constdouble SimplePI = 3.14;
public constbool Truth = true;
}

Referencing Constant Data:

class program
{

Public const string BestCollege = "EPCET";

static void Main(string[] args)


{
//print constant values defined by other type

Prep By: Sunitha Pramod Page 12


Console.WriteLine("student team const: {0}",
ConstData.BestStudentTeam);
Console.WriteLine("Simple PI const: {0}", ConstData.SimplePI);
Console.WriteLine("Truth const: {0}", ConstData.Truth);

//Print member level const.


Console.WriteLine("Bestcollege const: {0}", BestCollege);

//Print local-level const.


const int LocalFixedValue=10;
Console.WriteLine("Local const: {0}", LocalFixedValue);

Console.ReadLine();
}
}

Output:

student team const: 7 th ise


Simple PI const: 3.14
Truth const: True
Bestcollege const: EPCET
Local const: 10

const vs. readonly


const and readonly perform a similar function on data members, but they have a few
important differences.
[edit]
const
A constant member is defined at compile time and cannot be changed at runtime.
Constants are declared as a field, using the const keyword and must be initialized as they are
declared. For example;
public class MyClass
{
public const double PI = 3.14159;
}
PI cannot be changed in the application anywhere else in the code as this will cause a
compiler error.
• Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong,
char, float, double, decimal, or bool), an enumeration, a string literal, or a reference
to null.
• Since classes or structures are initialized at run time with the new keyword, and not at
compile time, you can't set a constant to a class or structure.
• Constants can be marked as public, private, protected, internal, or protected
internal.
• Constants are accessed as if they were static fields, although they cannot use the static

Prep By: Sunitha Pramod Page 13


keyword.
• To use a constant outside of the class that it is declared in, you must fully qualify it using
the class name.
[edit]

readonly
A readonly member is like a constant in that it represents an unchanging value. The
difference is that a readonly member can be initialized at runtime, in a constructor as well being
able to be initialized as they are declared. For example:
public class MyClass
{
public readonly double PI = 3.14159;
}

or
public class MyClass
{
public readonly double PI;

public MyClass()
{
PI = 3.14159;
}
}

Because a readonly field can be initialized either at the declaration or in a constructor,


readonly fields can have different values depending on the constructor used. A readonly field
can also be used for runtime constants as in the following example:
public static readonly uint l1 = (uint)DateTime.Now.Ticks;

Note:

• readonly members are not implicitly static, and therefore the static keyword can be
applied to a readonly field explicitly if required.

• A readonly member can hold a complex object by using the new keyword at
initialization.

• readonly members cannot hold enumerations.


Prep By: Sunitha Pramod Page 14
• Where a field is readonly, its value can be set only once, either in the class declaration, or
(for non-static fields only) in the class constructor.

[edit]

static
Use of the static modifier to declare a static member, means that the member is no
longer tied to a specific object. This means that the member can be accessed without creating an
instance of the class. Only one copy of static fields and events exists, and static methods
and properties can only access static fields and static events. For example:

public class Car


{
public static int NumberOfWheels = 4;
}

The static modifier can be used with classes, fields, methods, properties, operators,
events and constructors, but cannot be used with indexers, destructors, or types other than
classes.

static members are initialized before the static member is accessed for the first time,
and before the static constructor, if any is called. To access a static class member, use the
name of the class instead of a variable name to specify the location of the member. For example:
int i = Car.NumberOfWheels;

C# – Static Members:

A C# class can contain both static and non-static members. When we declare a member
with the help of the keyword static, it becomes a static member. A static member belongs to the
class rather than to the objects of the class. Hence static members are also known as class
members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static
or non-static. Remember that indexers in C# can't declared as static.

Prep By: Sunitha Pramod Page 15


Static Fields:
Static fields can be declared as follows by using the keyword static.

class MyClass
{
public static int x;
public static int y = 20;
}

When we declare a static field inside a class, it can be initialized with a value as shown
above. All un-initialized static fields automatically get initialized to their default values when the
class is loaded first time.

For example
// C#:static & non-static
using System;
class MyClass
{
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
}
}
The C# provides a special type of constructor known as static constructor to initialize the
static data members when the class is loaded at first. Remember that, just like any other static
member functions, static constructors can't access non-static data members directly.

Prep By: Sunitha Pramod Page 16


The name of a static constructor must be the name of the class and even they don't have
any return type. The keyword static is used to differentiate the static constructor from the normal
constructors. The static constructor can't take any arguments. That means there is only one form
of static constructor, without any arguments. In other way it is not possible to overload a static
constructor.

We can't use any access modifiers along with a static constructor.

// C# static constructor
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}
Note that static constructor is called when the class is loaded at the first time. However we
can't predict the exact time and order of static constructor execution. They are called before an
instance of the class is created, before a static member is called and before the static constructor
of the derived class is called.

Static Member Functions:


Inside a C# class, member functions can also be declared as static. But a static member
function can access only other static members. They can access non-static members only through
an instance of the class.

We can invoke a static member only through the name of the class. In C#, static
members can't invoked through an object of the class as like in C++ or JAVA.

Prep By: Sunitha Pramod Page 17


// C#:static & non-static
using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();
}
}
class MyClass : MyBase
{
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Base static method'
Console.WriteLine(MyClass.x);// Displays 25
}
}

Method Parameter Modifiers:

Prep By: Sunitha Pramod Page 18


C# provides a set of parameter modifiers that control how arguments are sent into(and
returned from) a given method.

.
Parameter Meaning in Life
Modifier
If a parameter is not marked with a parameter modifier, it is assumed to be an
(none)
input parameter passed by value. This is analogous to the IDL [in]
Attribute
This is analogous to an IDL [out] parameter. Output parameters are assigned
out
by the called member.

Analogous to the IDL [in, out] attribute. The value is assigned by the caller, but
ref
may be reassigned within the scope of the method call.

This parameter modifier allows you to send in a variable number of parameters


params
as a single parameter. A given method can only have a single
params modifier, and must be the final parameter of the method.

1. 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 keyword, a copy of the data is passed into
the function:
using System;

class Program
{

public 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 = 1000;
y = 2000;
return ans;
}

static void Main(string[] args)


{
int x=5,y=7;
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();
}

Prep By: Sunitha Pramod Page 19


}
Output:

Before call: X:5,y:7


Answer is: 12
After call: X: 5,y:7

2. The Reference (ref) parameters

Reference parameters don't pass the values of the variables used in the function member
invocation - they use the variables themselves. Rather than creating a new storage location for
the variable in the function member declaration, the same storage location is used, so the value of
the variable in the function member and the value of the reference parameter will always be the
same. Reference parameters need the ref modifier as part of both the declaration and the
invocation - that means it's always clear when you're passing something by reference.

using System;
class Program
{
public static void swap(ref string st1,ref string st2)
{
string temp;
temp = st1;
st1 = st2;
st2 = temp;

}
static void Main(string[] args)
{
string s1 = "First string";
string s2 = "second string";

Console.WriteLine("Before: {0},{1}", s1, s2);


swap(ref s1, ref s2);
Console.WriteLine("After: {0},{1}", s1, s2);
Console.ReadLine();
}

Output: Before: First string,second string

After: second string,First string

Here, the caller has assigned an initial value to local string data (s1 and s2). Once the call
to swap returns, s1 now contains the values “second string”, while s2 contains the values “First
string”.

3. The Output (out) parameters

Prep By: Sunitha Pramod Page 20


Like reference parameters, output parameters don't create a new storage location, but
use the storage location of the variable specified on the invocation. Output parameters need the
out modifier as part of both the declaration and the invocation - that means it's always clear
when you're passing something as an output parameter.

Output parameters are very similar to reference parameters. The only differences are:

• The variable specified on the invocation doesn't need to have been assigned a value
before it is passed to the function member. If the function member completes normally,
the variable is considered to be assigned afterwards (so you can then "read" it).
• The parameter is considered initially unassigned (in other words, you must assign it a
value before you can "read" it in the function member).
• The parameter must be assigned a value before the function member completes normally.

using System;
class Program
{
public static void Add(int x, int y, out int ans)
{
ans = x + y;

}
static void Main(string[] args)
{
int ans;
Add(90, 90, out ans);
Console.WriteLine("90+90={0}", ans);
Console.ReadLine();
}
}
OutPut: 90+90=180

//Returning multiple output parameters


using System;

class Program
{

public static void FillTheseValues(out int a, out string b, out bool c)


{
a=10;
b="hello";
c = true;
}

static void Main(string[] args)


{

Prep By: Sunitha Pramod Page 21


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("Bool is :{0}", b);
Console.ReadLine();
}
}

Output:

int is: 10

String is: hello

Bool is :True

4. The Params Modifier:

In C# 'params' parameter allows us to create a method that may be sent to a set of


identically typed arguments as a single logical parameter. To better understand this situation
let us see a program that calculates the average of any number of integers.

using System;

class Program
{

public static int Average(params int[] values)


{
int sum = 0;
for (int i = 0; i < values.Length; i++)
sum = sum + values[i];

return (sum / values.Length);


}

static void Main(string[] args)


{
//pass int values in comma separated form

int average;
average = Average(30, 40, 70);

Console.WriteLine("The average is: {0}", average);

Prep By: Sunitha Pramod Page 22


//Pass an array of int
int[] data ={ 30, 40, 70 };
average=Average(data);

Console.WriteLine("The avearge of the int array ele:{0}",average);


Console.ReadLine();
}
}

Output:
The average is: 46
The avearge of the int array ele:46

Understanding Value Types and Reference Types:

.Net data type may be value-based or reference-based. Value-based types, which


include all nyumerical dat types(int,float, etc) as well as enumerations and structures, are
allocated on stack. Value types can be quickly removed from memory once they fall out of the
defining scope

Prep By: Sunitha Pramod Page 23


Prep By: Sunitha Pramod Page 24
Differences between value type and Reference type:

• Value types are stored in stack


• Reference types are stored in heap
• When we assign one value type to another value type, it is cloned and the two instances
operate independently.
For eg, a=b; A new memory ;location is allocated for a and it is hold the value
individually. Changing the value of b does not affect a.
• When reference type is assigned to another reference type, the two reference share the
same instance and change made by the one instance affects the other.
For eg, a=b; a reference (pointer) is created for a and both a and b now points to same
address. Any alteration made to b will affect a.
• Value types cannot be set to null
• Reference types can be set to null
• Converting value type to reference type is called boxing.
• Converting reference type to value type to called unboxing.
• Value types are by default passed by value to other methods.
• Reference types are by default passed by reference to other methods.
• The stack holds value type variables plus return addresses for functions. All numeric types, ints, floats a
bools and structs are value types.

Prep By: Sunitha Pramod Page 25


• The heap hold variables created dynamically- known as reference variables and mainly instances of c
stored in two places; there's a hidden pointer to the place in the heap where the data is stored.

• Another distinction between value and reference type is that a value type is derived from System.ValueT
from System.Object.

Value Types Containing Reference Types:

using System;

class ShapeInfo
{
public string infoString;
public ShapeInfo(string info)
{
infoString = info;
}
}

struct MyRectangle
{
//The MyRectangle structure conatins a reference type member

public ShapeInfo rectInfo;

public int top, left, bottom, right; // value types

public MyRectangle(string info)


{
rectInfo = new ShapeInfo(info);
top = left = 10;
bottom = right = 100;
}
}

class program
{
public static void Main(string[] args)
{
//create the first MyRectangle

Console.WriteLine("->Creating r1");
MyRectangle r1 =new MyRectangle("This is my first rect");

//now assign a new MyRectangle to r1


Console.WriteLine("->Assigning r2 to r1");
MyRectangle r2;
r2=r1;

//changing values of r2
Console.WriteLine("->Changing values of r2");
r2.rectInfo.infoString="This is new info";
r2.bottom=4000;

Prep By: Sunitha Pramod Page 26


//print values

Console.WriteLine("->Values after change");


Console.WriteLine("->r1.rectInfo.infoString :{0}",r1.rectInfo.infoString);
Console.WriteLine("->r2.rectInfo.infoString :{0}",r2.rectInfo.infoString);
Console.WriteLine("->r1.bottom:{0}",r1.bottom);
Console.WriteLine("->r2.bottom :{0}",r2.bottom);

Console.ReadLine();
}
}

Output:

->Creating r1
->Assigning r2 to r1
->Changing values of r2
->Values after change
->r1.rectInfo.infoString :This is new info
->r2.rectInfo.infoString :This is new info
->r1.bottom:100
->r2.bottom :4000

Passing Reference Types by Value:


using System;

class person
{
public string fullName;
public int age;

public person() { }

public person(string n, int a)


{
fullName = n;
age = a;
}

public void printInfo()


{
Console.WriteLine("{0} is {1} years old", fullName, age);
}
}

class program
{
public static void SendAPersonByValue(person p)
{
//change the age of p
p.age = 99;

Prep By: Sunitha Pramod Page 27


//will the caller see this reassignment
p = new person("nikki", 25);
}

public static void Main(string[] args)


{
//passing reference types by value
Console.WriteLine("******passing person object by value********");
person smith = new person("smith", 10);
Console.WriteLine("Before by value call, person is:");
smith.printInfo();

SendAPersonByValue(smith);
Console.WriteLine("After by value call, person is:");
smith.printInfo();

Console.ReadLine();
}
}
Output:

******passing person object by value********

Before by value call, person is:

smith is 10 years old

After by value call, person is:

smith is 99 years old

Passing Reference Types by Reference:


using System;

class person
{
public string fullName;
public int age;

public person() { }
public person(string n, int a)
{
fullName = n;
age = a;
}

public void printInfo()


{
Console.WriteLine("{0} is {1} years old", fullName, age);
}
}

Prep By: Sunitha Pramod Page 28


class program
{
public static void SendAPersonByReference(ref person p)
{
//change the age of p
p.age = 99;

//will the caller see this reassignment


p = new person("nikki", 25);
}

public static void Main(string[] args)


{
//passing reference types by value
Console.WriteLine("******passing person object by
reference********");
person smith = new person("smith", 10);
Console.WriteLine("Before by ref call, person is:");
smith.printInfo();

SendAPersonByReference(ref smith);
Console.WriteLine("After by ref call, person is:");
smith.printInfo();

Console.ReadLine();
}
}

Output:

******passing person object by reference********

Before by ref call, person is:

smith is 10 years old

After by ref call, person is:

nikki is 25 years old

Understanding Boxing and Unboxing Operations:


Boxing and unboxing is a essential concept in C# type system. With Boxing and unboxing
one can link between value-types and reference-types by allowing any value of a value-type to
be converted to and from type object. Boxing and unboxing enables a unified view of the type
system wherein a value of any type can ultimately be treated as an object.

Prep By: Sunitha Pramod Page 29


• Converting value type to reference type is called boxing by storing the variable in a
System.Object.
• Converting reference type to value type to called unboxing
The following example shows both boxing and unboxing:

class Test
{
Public static void Main()
{
int i=1;
object o = i; //boxing
int j=(int) o; //unboxing
}
}

An int value can be converted to object and back again to int

• When a variable of a value type needs to be converted to a reference type, an object box is
allocated to hold the value, and the value is copied into the box.
• Unboxing is just opposite. When an object box is cast back to its original value type, the
value is coped out of the box and into the appropriate storage location.

using System;

class program
{

public static void Main(string[] args)


{
Int32 x1 = 10;
object o1 = x1; // Implicit boxing
Console.WriteLine("The Object o1 = {0}", o1); // prints out 10
//-----------------------------------------------------------
Int32 x2 = 10;
object o2 = (object)x2; // Explicit Boxing
Console.WriteLine("The object o2 = {0}", o2); // prints out 10
Console.ReadLine();
}
}

Output:

Prep By: Sunitha Pramod Page 30


The Object o1 = 10
The object o2 = 10

Unboxing Custom Value Types:


using System;
struct Mypoint
{
public int x, y;
}
class program
{
//compiler error, since to access the field data of Mypoint, you must
//first unbox the parameter. This is done in the following method.
/*static void UseBoxedMypoint(object o)
{
Console.WriteLine(“{0},{1}}”,o.x,o.y);
}*/

static void UseBoxedMypoint(object o)


{
if (o is Mypoint)
{
Mypoint p = (Mypoint)o;
Console.WriteLine("{0},{1}", p.x, p.y);
}

else
Console.WriteLine("You did not send a Mypoint");
}

public static void Main(string[] args)


{
Mypoint p;
p.x = 10;
p.y = 20;
UseBoxedMypoint(p);
Console.ReadLine();
}
}

Output:

10,20

Working with .NET Enumerations:

An enum is a value type with a set of related named constants often referred to as an
enumerator list.

Example:

Prep By: Sunitha Pramod Page 31


enum EmpType
{
Manager, // =0
Grunt, // =1
Contractor, // =2
VP // =3
}

Note: In C#, the numering scheme sets the first element to zero {0} by default, followed by an
n+1 progression.

// begin numbering at 102

enum EmpType
{
Manager = 102, // = 0
Grunt, // = 103
Contractor, // = 104
VP // = 105
}

//Elements of an enumeration need not be sequential


enum EmpType
{
Manager = 10,
Grunt = 1,
Contractor = 5,
VP = 7
}

The System.Enum Base Class:

This base class defines a number of methods(mentioned in the following table) that allow you
to integrate and transform a given enumeration.

Method Name Description

GetUnderlyingType() Returns the data type used to represent the enumeration.

Prep By: Sunitha Pramod Page 32


Format() Returns the string associated with the enumeration.

GetName() Retrieves a name (or an array containing all names) for the
GetNames() constant in the specified enumeration that has the specified value.

GetValues() Returns the members of the enumeration.

Property Name Description

IsDefined() Returns whether a given string name is a member of the current


enumeration.

using System;

enum EmpType
{
Manager, // = 0
Grunt, // = 1
Contractor, // = 2
VP // = 3
}

class program
{
public static void Main(string[] args)
{
//print information for the EmpType enumeration.
Array obj = Enum.GetValues(typeof(EmpType));
Console.WriteLine("This enum has {0} members:", obj.Length);

foreach (EmpType e in obj)


{
Console.WriteLine("String name: {0}", e.ToString());
Console.WriteLine("int: ({0})", Enum.Format(typeof(EmpType), e, "D"));
Console.WriteLine("hex: ({0})", Enum.Format(typeof(EmpType), e, "X"));
}

Console.ReadLine();
}
}

Output:
This enum has 4 members:

String name: Manager

Prep By: Sunitha Pramod Page 33


int: (0)

hex: (00000000)

String name: Grunt

int: (1)

hex: (00000001)

String name: Contractor

int: (2)

hex: (00000002)

String name: VP

int: (3)

hex: (00000003)

using System;

enum EmpType
{
Manager, // = 0
Grunt, // = 1
Contractor, // = 2
VP // = 3
}

class program
{
public static void Main(string[] args)
{
//Does EmpType have a SalesPerson value?

if(Enum.IsDefined(typeof(EmpType), "SalesPerson"))
Console.WriteLine("Yes we have sales people");
else
Console.WriteLine("no sales people");
Console.ReadLine();
}
}

Output:
no sales people

Prep By: Sunitha Pramod Page 34


The Master Class: System.Object
The Object class is the base class for every type. All data types derived from
System.Object

System.Object defines a set of instance-level and class-level(static) members supported


by every type in the .NET universe. Some of the instance-level members are declared using the
virtual keyword and can therefore be overridden by a derived class:

//The topmost class in the .NET universe: System.Object

namespace System

Public class Object

public Object();

public virtual Boolean Equals(Object obj);

public virtual Int32 GetHashCode();

public Type GetType();

public virtual String ToString();

protected virtual void Finalize();

protected Object MemberwiseClone();

public static bool Equals(Object objA, Object objB);

public static bool ReferenceEquals(Object objA, Object objB);

Method Purpose
whether the object is the same as the one referred
public virtual bool Equals(object ob)
to by ob.
public static bool Equals(object ob1, whether ob1 is the same as ob2.

Prep By: Sunitha Pramod Page 35


object ob2)
Performs shutdown actions prior to garbage
protected Finalize()
collection.
public virtual int GetHashCode() Returns the hash code.
public Type GetType() Return the type of an object.
Makes a "shallow copy" of the object. (The
protected object MemberwiseClone() members are copied, but objects referred to by
members are not.)
public static bool
ReferenceEquals(object ob1, object whether ob1 and ob2 refer to the same object.
ob2)
Returns a string that describes the object. It is
public virtual string ToString() automatically called when an object is output
using WriteLine().

The following example contains two calls to the default implementation of


System.Object.Equals(System.Object) .

using System;
class MyClass
{
static void Main()
{
Object obj1 = new Object();
Object obj2 = new Object();
Console.WriteLine(obj1.Equals(obj2));
obj1 = obj2;
Console.WriteLine(obj1.Equals(obj2));
}
}
The output is

False

True

The following example demonstrates the System.Object.Equals(System.Object) method.


using System;

public class MyClass {


public static void Main() {
string s1 = "Tom";
string s2 = "Carol";
Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}",
s1, s2, Object.Equals(s1, s2));

s1 = "Tom";

Prep By: Sunitha Pramod Page 36


s2 = "Tom";
Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}",
s1, s2, Object.Equals(s1, s2));
}
}

The output is

Object.Equals("Tom", "Carol") => False

Object.Equals("Tom", "Tom") => True

Default Behavior of System.Object:

using System;

public class Employee


{
public string firstName;
public string lastName;

public Employee(string firstName, string lastName)


{
this.firstName = firstName;
this.lastName = lastName;
}
public void Display()
{
Console.WriteLine("firstName = " + firstName);
Console.WriteLine("lastName = " + lastName);
}

class MainClass
{

public static void Main()


{
Console.WriteLine("Creating Employee objects");
Employee myEmployee = new Employee("A", "M");
Employee myOtherEmployee = new Employee("B", "N");

Console.WriteLine("myEmployee details:");
myEmployee.Display();

Console.WriteLine("myOtherEmployee details:");
myOtherEmployee.Display();

Console.WriteLine("myEmployee.ToString() = " + myEmployee.ToString());


Console.WriteLine("myEmployee.GetType() = " + myEmployee.GetType());
Console.WriteLine("myEmployee.GetHashCode() = " +
myEmployee.GetHashCode());

Prep By: Sunitha Pramod Page 37


Console.WriteLine("Employee.Equals(myEmployee, myOtherEmployee) = " +
Employee.Equals(myEmployee, myOtherEmployee));

Console.WriteLine("Employee.ReferenceEquals(myEmployee,
myOtherEmployee) = " + Employee.ReferenceEquals(myEmployee,
myOtherEmployee));

Console.ReadLine();

Output:

Creating Employee objects


myEmployee details:
firstName = A
lastName = M
myOtherEmployee details:
firstName = B
lastName = N
myEmployee.ToString() = Employee
myEmployee.GetType() = Employee
myEmployee.GetHashCode() = 45653674
Employee.Equals(myEmployee, myOtherEmployee) = False
Employee.ReferenceEquals(myEmployee, myOtherEmployee) = False

Overriding Some Default Behaviors of System.Object:

using System;
using System.Text;

class Person
{
public Person(string fname, string lname, string ssn, byte a)
{
FirstName = fname;
LastName = lname;
SSN = ssn;
age = a;
}

public string FirstName;


public string LastName;
public string SSN;
public byte age;

public override bool Equals(object o)//Overriding System.Object.Equals()

Prep By: Sunitha Pramod Page 38


{
Person temp = (Person)o;
if(temp.FirstName == this.FirstName &&
temp.LastName == this.LastName &&
temp.SSN == this.SSN &&
temp.age == this.age)
{
return true;
}
else
return false;
}

public override string ToString()//Overriding System.Object.Tostring()


{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("[FirstName= {0}", this.FirstName);
sb.AppendFormat(" LastName= {0}", this.LastName);
sb.AppendFormat(" SSN= {0}", this.SSN);
sb.AppendFormat(" Age= {0}]", this.age);

return sb.ToString();
}

public override int GetHashCode()//Overriding System.Object.GetHashCode()


{
return SSN.GetHashCode();
}
}

//Testing the overriden Members

class MainClass
{
public static void Main(string[] args)
{
Person p1 = new Person("A", "B", "222-22-2222", 98);
Person p2 = new Person("A", "B", "222-22-2222", 98);

Console.WriteLine("Hash code of p1={0}", p1.GetHashCode());


Console.WriteLine("Hash code of p2={0}", p2.GetHashCode());

Console.WriteLine("String of p1={0}", p1.ToString());


Console.WriteLine("String of p2={0}", p2.ToString());

if (p1.Equals(p2))
Console.WriteLine("->p1 and p2 have same state");
else
Console.WriteLine("-> p1 and p2 have diffrent state");

Console.WriteLine("P3 and P4 have same state: {0}", object.Equals(p1, p2));


Console.ReadLine();
}
}

Output:

Prep By: Sunitha Pramod Page 39


Hash code of p1=-1663800364
Hash code of p2=-1663800364
String of p1=[FirstName= A LastName= B SSN= 222-22-2222 Age= 98]
String of p2=[FirstName= A LastName= B SSN= 222-22-2222 Age= 98]
->p1 and p2 have same state
P3 and P4 have same state: True

Note: Need to reference System.Text to access StringBuilder type.

.NET Array Types:


In C#, an array index starts at zero. That means, first item of an array will be stored at 0th
position. The position of the last item on an array will total number of items - 1.

In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a
predefined number of items, while size of dynamic arrays increases as you add new items to the
array. You can declare an array of fixed length or dynamic.

For example, the following like declares a dynamic array of integers.


int [] intArray;

The following code declares an array, which can store 5 items starting from index 0 to 4.

int [] intArray;
intArray = new int[5];

The following code declares an array that can store 100 items starting from index 0 to 99.

int [] intArray;
intArray = new int[100];

Arrays can be divided into four categories. These categories are single-dimensional
arrays, multidimensional arrays or rectangular arrays, jagged arrays, and mixed arrays.

In C#, arrays are objects. That means declaring an array doesn't create an array. After
declaring an array, you need to instantiate an array by using the "new" operator

Prep By: Sunitha Pramod Page 40


The following code declares and initializes an array of three items of integer type.

int [] intArray;
intArray = new int[3] {0, 1, 2};

The following code declares and initializes an array of 5 string items.


string[] strArray = new string[5] {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

You can even direct assign these values without using the new operator.
string[] strArray = {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

You can initialize a dynamic length array as following


string[] strArray = new string[] {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

Arrays As Parameters (and Return Values):


Once you created an array, you are free to pass it as a parameter and receive it as a
member return vales.

Example:
using System;

class program
{
static void PrintArrays(int[] MyInt)
{
Console.WriteLine("The int array is");
for (int i = 0; i < MyInt.Length; i++)
Console.WriteLine(MyInt[i]);
}

static string[] GetStringArray()


{
string[] TheStrings = { "Hello", "What", "That", "stringarray" };
return TheStrings;//return a string array
}

public static void Main(string[] args)


{
int[] ages ={ 10, 20, 30, 40 };
PrintArrays(ages); //passing an array as parameter

string[] strs = GetStringArray(); //Receiving a string array in a var strs

Console.WriteLine("The string array is");


foreach (string s in strs)
Console.WriteLine(s);

Console.ReadLine();

Prep By: Sunitha Pramod Page 41


}
}
Output:

The int array is

10

20

30

40

The string array is

Hello

What

That

stringarray

Working with Multidimensional Arrays:

using System;

class program
{

public static void Main(string[] args)


{
//A rectangular MD array
int[,] a;
a = new int[3, 3];

//populate (3*3) array.


for (int i = 0; i <3 ; i++)
for (int j = 0; j <3; j++)
a[i, j] = i * j;

//print (3*3) array


for (int i = 0; i <3; i++)
{
for (int j = 0; j <3; j++)
{
Console.Write(a[i, j] + "\t");
}

Console.WriteLine();
}
Console.ReadLine();
}

Prep By: Sunitha Pramod Page 42


}

0 0 0

0 1 2

0 2 4

The System.Array Base Class:

The Array class, defined in the System namespace, is the base class for arrays in C#.
Array class is an abstract base class but it provides CreateInstance method to construct an array.
The Array class provides methods for creating, manipulating, searching, and sorting arrays.

Table 1 describes Array class properties.

IsFixedSize Return a value indicating if an array has a fixed size or not.


IsReadOnly Returns a value indicating if an array is read-only or not.
Length Returns the total number of items in all the dimensions of an array.
Rank Returns the number of dimensions of an array.

Table 1: The System.Array Class Properties

Table 2 describes some of the Array class methods.

BinarySearch This method searches a one-dimensional sorted Array for a value, using a
binary search algorithm.
Clear This method removes all items of an array and sets a range of items in the array
to 0.
Copy This method copies a section of one Array to another Array and performs
type casting and boxing as required.
CopyTo This method copies all the elements of the current one-dimensional Array to
the specified one-dimensional Array starting at the specified destination
Array index.
CreateInstance This method initializes a new instance of the Array class.
GetLength This method returns the number of items in an Array.
Reverse This method reverses the order of the items in a one-dimensional Array or in a
portion of the Array.

Prep By: Sunitha Pramod Page 43


Sort This method sorts the items in one-dimensional Array objects.

Write C# program to demonstrate the methods of Array class i,e copy, sort, reverse, and clear

using System;

class program
{

public static void Main(string[] args)


{
//Array of string

string[] names = { "amir", "sharuk", "salman", "Hrithik" };

//print the names


Console.WriteLine("\nNames are");
for(int i=0;i<names.Length;i++)
Console.WriteLine("{0}",names[i]);

//copy source array(names) to destination array(str)


string[] str = new string[5];
Array.Copy(names, str, 4);
Console.WriteLine("\nAfter copy the new name array is");
for (int i = 0; i < str.Length; i++)
Console.WriteLine("{0}", str[i]);

//print the sorted array


Array.Sort(names);
Console.WriteLine("\nAfter sorting array is");
for (int i = 0; i < names.Length; i++)
Console.WriteLine("{0}", names[i]);

//Reverse name array and print it


Array.Reverse(names);

Console.WriteLine("\nThe reverse array ");


for(int i=0;i<names.Length;i++)
Console.WriteLine("{0}",names[i]);

//clear out all except hrithik


Array.Clear(names,1,3);

Console.WriteLine("\nclear out all except hrithik");


for(int i=0;i<names.Length;i++)
Console.WriteLine("{0}",names[i]);

System.Console.ReadLine();
}

Prep By: Sunitha Pramod Page 44


}

Output:
Names are

amir

sharuk

salman

Hrithik

After copy the new name array is

amir

sharuk

salman

Hrithik

After sorting array is

amir

Hrithik

salman

sharuk

The reverse array

sharuk

salman

Hrithik

amir

clear out all except hrithik

sharuk

Prep By: Sunitha Pramod Page 45


Jagged Arrays:
Jagged arrays are often called array of arrays. An element of a jagged array itself is an
array. For example, jagged arrays is an array of integers containing another array of integers.

int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} };

Defining Custom Namespaces:


Namespaces are a way to define the classes and other types of information into one
hierarchical structure. System is the basic namespace used by every .NET code.

A namespace can be created via the Namespace keyword.

Write a C# program to create namespace called MyShapes with classes circle. triangle,
rectangle

using System;

namespace MyShapes
{
public class circle
{
public void cirdisp()
{
Console.WriteLine(3.14 * 2 * 2);
}

public class Triangle


{
public void tridisp()
{
Console.WriteLine(0.5 * 2 * 2);
}

public class Rectangle


{
public void recdisp()
{
Console.WriteLine(2 * 2);

Prep By: Sunitha Pramod Page 46


}

}
}

using System;
using MyShapes;

class Class1
{
public static void Main()
{
circle c = new circle();
Triangle t = new Triangle();
Rectangle r = new Rectangle();

c.cirdisp();
t.tridisp();
r.recdisp();

Console.ReadLine();
}

Output

Creating Nested namespace:

namespace Books
{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}
}
}
}

Prep By: Sunitha Pramod Page 47


using Books;
class HelloWorld
{
public static void Main()
{
Inventory.AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

output:

Adding Inventory via MyMethod

Final Notes

The namespaces are building blocks for the .NET way of software development. The
namespaces wide opens the doors for 3'd party and project specific custom components and class
libraries.

Prep By: Sunitha Pramod Page 48

Você também pode gostar