Vous êtes sur la page 1sur 55

Chapter 3: C# Language Fundamentals

C# demands that all program logic is contained within a type defnition (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 defned 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"#rite$ine(%Hello &orl'%!(
return )(
*
*
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 frst of Main( ) is defned 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 comman' line arguments"
/ Ma+e some ob,ects"
--.eturn a /alue to the system"
*
// !o return type, no arguments.
public static "oid Main(!
{
-- Ma+e some ob,ects"
*
Page 1
// Integer return type, no arguments.
public static int Main(!
{
/ Ma+e some ob,ects"
/ .eturn a /alue to the system"
*
Processing Command Line Parameters
// command line arguments.
using System(
classHelloClass
{
public static int Main(string[ args!
{
Console"#rite$ine(%00000 Comman' line args 00000%!(
for(int 1 2 )( 1 3args"$ength( 144!
Console"#rite$ine(%Arg: {)* %5 args[1!(
Console"#rite$ine(%Hello #orl'6%!(
return )(
*
*
Alternative to the standard for loop C# "foreach" keyword.
// !otice we ha"e no need to chec# the si$e of the array when using
//%foreach%.
public static int Main(string[ args!
{
foreach&string s in args!
Console"#rite$ine(%Arg: {)* %5 s!(
"""
*
7utPut:
Page 2
Write a C# program to find sum and avg of two numbers
using System(
class program
{
static /oi' Main(string[ args!
{
string s85 s9(
int n85 n95 sum(
float a/g(
Console"#rite$ine(%:nter the first number%!(
s8 2 Console".ea'$ine(!(
Console"#rite$ine(%:nter the secon' number%!(
s9 2 Console".ea'$ine(!(
n8 2 int"Parse(s8!(
n9 2 int"Parse(s9!(
sum 2 n8 4 n9(
a/g 2 sum - 9(
Console"#rite$ine(%sum is {)* an' a/g is {8*%5 sum5a/g!(
Console".ea'$ine(!(
*
*
Output:
Enter the first number
3
Enter the second
number 7
sum is 10 and avg is 5
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
;sing System(
Class HelloClass
{
public static int Main(string[ args!
{
// 'rror( )se of unassigned local "aria*le( +ust use %new%.
HelloClass c8(
c8"SomeMetho'(!(
return )(
*
*
To illustrate the proper procedure for class instantiation, observe the following update:
// +a#e ,elloClass types correctly using the C# %new% #eyword.
;sing System(
classHelloClass
{
public static int Main(string[ args!
{
/ -ou can declare and create a new o*.ect in a single line...
HelloClass c8 2 new HelloClass(!(
/ ...or *rea# declaration and creation into two lines.
HelloClass c9(
c9 2 new HelloClass(!(
return )(
*
*
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:
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"#rite$ine(%<n<n=efault Constr calle'%!(
*
public helloclass(string msg!
{
Console"#rite$ine(%Parametri>e' constr calle'%!(
usermessage 2 msg(
*
static int Main(string[ args!
{
helloclass c8 2 ne& helloclass(!(--'efault const calle'"
Console"#rite$ine(%?alue of usermessage:{)*<n<n%5c8"usermessage!(
helloclass c9(
c9 2 ne& helloclass(%testing 85 95 @%!(--para constr calle'
Console"#rite$ine(%/alue of usermessage:{)*%5 c9"usermessage!(
Console".ea'$ine(!(
return )(
*--en' 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
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.
/rite a c# program for construtors, static constructors
and destructors0
using System(
class Test9
{
static int i(
static Test9(!
{ -- a constructor for the entire class calle'
--once before the first ob,ect create'
i 2 A(
Console"#rite$ine(%insi'e static construtor"""%!(
*
public Test9(!
{
Console"#rite$ine(%insi'e regular construtor""" i2{)*%5 i!(
*
BTest9(!
{ -- 'estructor (hopefully! calle' for each ob,ect
Console"#rite$ine(%insi'e 'estructor%!(
*
static /oi' Main(string[ args!
{
Console"#rite$ine(%Test9%!(
Test9 t82ne& Test9(!(
Test9 t92ne& Test9(!(
Console".ea'$ine(!(
*
*
Output:
inside static construtor...
Test2
inside regular construtor... i=4
inside regular construtor... i=4
Defining an Application Object:
Page
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"#rite$ine(%<n<n=efault Constr calle'%!(
*
public helloclass(string msg!
{
Console"#rite$ine(%Parametri>e' constr calle'%!(
usermessage 2 msg(
*
public /oi' printmessage(!
{
Console"#rite$ine(%message is {)*%5 usermessage!(
*
*--en' of helloclass
Class helloapp
{
staticint Main(string[ args!
{
helloclass c8 2 ne& helloclass(%Hey there"""""""""% !(
c8"printmessage(!(
return )(
*
*
OutPut: Parametri>e' constr calle'
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.
Page !
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.
/ Ma+e use of the Console class to perform basic C7"
using System(
class helloclass
{
static int Main(string[ args!
{
Console"#rite(%<n<n:nter your name: %!(
string s 2 Console".ea'$ine(!(
Console"#rite$ine(%Dame is {)*<n%5 s!(
Console"#rite(%:nter your age: %!(
s 2 Console".ea'$ine(!(
Console"#rite$ine(%you are {)* years ol': %5 s!(
Console".ea'$ine(!(
return )(
*
*
7utput:
:nter your name: smith
Dame is smith
:nter your age: 9E you
are 9E years ol':
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 theCnt 2 F)(
'ouble the=ouble 2 F"FF(
bool theGool 2 true(
Console"#rite$ine(% Cnt is: {)*<n =ouble is: {8*<n Gool is : {9*%5
theCnt5 the=ouble5 theGool!(
Console".ea'$ine(!(
Page "
return )(
*
*
7utPut: int
is: F)
=ouble is: F"FF
Gool 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# 1ormat +eaning in life
Character
C or c Used to format currency. By default, the fag will prefx 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 fag 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 fxed 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 c#aracter
:1ample:
using System(
class helloclass
{
static int Main(string[ args!
{
Console"#rite$ine(%C format: {):C*%5 FFFHF"FHI!(
Console"#rite$ine(%=I format: {):=I*%5 FFFFF!(
Console"#rite$ine(%: format: {)::*%5 FFFFF"IJAE@!(
Console"#rite$ine(%K@ format: {):K@*%5 FFFFF"FFFF!(
Console"#rite$ine(%D format: {):D*%5 FFFFF!(
Console"#rite$ine(%L format: {):L*%5 FFFFF!(
Console"#rite$ine(%1 format: {):1*%5 FFFFF!(
Console".ea'$ine(!(
return )(
*
*
7utput:
C format: MFF5FHF"FF
Page $
=I format: ))FFFFF
: format: F"FFFFIJ:4))A
K@ format: 8)))))"))) D
format: FF5FFF"))
L format: 8HJFK
1 format: 8HJFf
Establishing Member Visibilty:
using System(
class someclass
{
--Accessible any&here"
public /oi' publicmetho'(!
{
Console"#rite$ine(%?isiblity of member is public%!(
*
--Accessible from someclass an' any 'eri/e' class
protecte' /oi' protecte'metho'(!
{
Console"#rite$ine(%?isiblity of member is protecte'%!(
*
--Accessible only from someclass
pri/ate /oi' pri/atemetho'(!
{
Console"#rite$ine(%?isiblity of member is pri/ate%!(
*
--Accessible &ithin same assembly
internal /oi' internalmetho'(!
{
Console"#rite$ine(%?isiblity of member is internal%!(
*
--ASsemblyNprotecte' access
protecte'internal /oi' protecte'internalmetho'(!
{
Console"#rite$ine(%?isiblity of member is protecte'internal%!(
*
--;nmar+e' members are pri/ate by 'efault in c#
/oi' somemetho'(! { *
*
class helloclass
{
static int Main(string[ args!
Page 1%
{
someclass c 2 ne& someclass(!(
c"publicmetho'(!(
c"internalmetho'(!(
c"protecte'internalmetho'(!(
--c"protecte'metho'(!(
:rror --c"pri/atemetho'(!(
:rror --c"somemetho'(!( :rror
Console".ea'$ine(!(
return )(
*
*
7utput:
?isiblity of member is public
?isiblity of member is internal
?isiblity of member is protecte'internal
Default values of class member variables:
using System(
class program
{
public int myCnt( -- set to )
Public string myString( --set to null
Public bool myGool( -- set to false
Public ob,ect my7b,( --set to null
static /oi' Main(string[ args!
{
program p 2 ne& program(!(
Console"#rite$ine(%'efault int /alue is: {)*<n 'efault string
/alue is: {8*<n 'efault bool /alue is: {9*<n 'efault ob, /alue
is: {@*<n%5 p"myCnt5 p"myString5 p"myGool5 p"my7b,!(
Console".ea'$ine(!(
*
*
7utput:
'efault int /alue is: )
'efault string /alue is:
'efault bool /alue is: Kalse
'efault ob, /alue is:
Member Variable Initialization Syntax:
Page 11
using System(
class program
{
public int myCnt2F(
Public string myString2%hello%(
Public bool myGool2true(
Public ob,ect my7b,2FF"FFF(
static /oi' Main(string[ args!
{
program p 2 ne& program( !(
Console"#rite$ine(%int /alue is: {)*<n string /alue is: {8*<n bool /alue is:
{9*<n ob, /alue is: {@*<n%5 p"myCnt5 p"myString5 p"myGool5 p"my7b,!(
Console".ea'$ine(!(
*
*
7utput:
int /alue is: F
string /alue is: hello
bool /alue is: True
ob, /alue is: FF"FFF
Defining Constant Data:
using System(
class Const=ata
{
public conststring GestStu'entTeam 2 %I th ise%(
public const'ouble SimplePC 2 @"8A(
public constbool Truth 2 true(
*
Referencing Constant Data:
class program
{
Public const string GestCollege 2 %:PC:T%(
static /oi' Main(string[ args!
{
--print constant /alues 'efine' by other type
Page 12
Console"#rite$ine(%stu'ent team const: {)*%5
Const=ata"GestStu'entTeam!(
Console"#rite$ine(%Simple PC const: {)*%5 Const=ata"SimplePC!(
Console"#rite$ine(%Truth const: {)*%5 Const=ata"Truth!(
--Print member le/el const" Console"#rite$ine(%Gestcollege
const: {)*%5 GestCollege!(
--Print localNle/el const"
const int $ocalKi1e'?alue28)(
Console"#rite$ine(%$ocal const: {)*%5 $ocalKi1e'?alue!(
Console".ea'$ine(!(
*
*
7utput:
stu'ent team const: I th ise
Simple PC const: @"8A
Truth const: True
Gestcollege const: :PC:T
$ocal const: 8)
const vs. readonly
const and rea'only 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 'ouble PC 2 @"8A8EF(
*
PC 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, 'ouble, 'ecimal, or bool), an enumeration, a string literal, or a reference
to null.
Since classes or structures are initialized at run time with the ne& keyword, and not at
compile time, you can't set a constant to a class or structure.
Constants can be marked as public, pri/ate, protecte', internal, or protecte'
internal.
Constants are accessed as if they were static fields, although they cannot use the static
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 rea'only 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 rea'only 'ouble PC 2 @"8A8EF(
*
or
public class MyClass
{
public rea'only 'ouble PC(
public MyClass(!
{
PC 2 @"8A8EF(
*
*
Because a rea'only field can be initialized either at the declaration or in a constructor,
rea'only fields can have different values depending on the constructor used. A rea'only field
can also be used for runtime constants as in the following example:
public static rea'only uint l8 2 (uint!=ateTime"Do&"Tic+s(
Note:
rea'only members are not implicitly static, and therefore the static keyword can be
applied to a rea'only field explicitly if required.
A rea'only member can hold a complex object by using the ne& keyword at
initialization.
rea'only members cannot hold enumerations.
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 Dumber7f#heels 2 A(
*
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 2 Car"Dumber7f#heels(
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.
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.
Page 1
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.
Page 1!
// 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:
Page 1"
C# provides a set of parameter modifiers that control how arguments are sent into(and
returned from) a given method.
.
2arameter +eaning in 3ife
+odifier
(none)
If a parameter is not marked with a parameter modifer, it is assumed to be an
input parameter passed by value. This is analogous to the IDL [in]
Attribute
out
This is analogous to an IDL [out] parameter. Output parameters are assigned
by the called member.
ref
Analogous to the IDL [in, out] attribute. The value is assigned by the caller, but
may be reassigned within the scope of the method call.
params
This parameter modifer allows you to send in a variable number of parameters
as a single parameter. A given method can only have a single
params modifer, and must be the fnal 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 A''(int 15 int y!
{
int ans 2 1 4 y(
/ Caller &ill not see these changes as you are mo'ifying a copy
/ of the original 'ata
1 2 8)))(
y 2 9)))(
return ans(
*
static /oi' Main(string[ args!
{
int 12E5y2I(
Console"#rite$ine(%Gefore call: L:{)*5y:{8*%515y!(
Console"#rite$ine(%Ans&er is: {)*%5A''(15y!!(
Console"#rite$ine(%After call: L: {)*5y:{8*%515y!(
Console".ea'$ine(!(
*
Page 1$
*
7utput:
Gefore call: L:E5y:I
Ans&er is: 89
After call: L: E5y:I
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 /oi' s&ap(ref string st85ref string st9!
{
string temp(
temp 2 st8(
st8 2 st9(
st9 2 temp(
*
static /oi' Main(string[ args!
{
string s8 2 %Kirst string%(
string s9 2 %secon' string%(
Console"#rite$ine(%Gefore: {)*5{8*%5 s85 s9!(
s&ap(ref s85 ref s9!(
Console"#rite$ine(%After: {)*5{8*%5 s85 s9!(
Console".ea'$ine(!(
*
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
Page 2%
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 /oi' A''(int 15 int y5 out int ans!
{
ans 2 1 4 y(
*
static /oi' Main(string[ args!
{
int ans(
A''(F)5 F)5 out ans!(
Console"#rite$ine(%F)4F)2{)*%5 ans!(
Console".ea'$ine(!(
*
*
7utPut: F)4F)28H)
--.eturning multiple output parameters
using System(
class Program
{
public static /oi' KillThese?alues(out int a5 out string b5 out bool c!
{
a28)(
b2%hello%(
c 2 true(
*
static /oi' Main(string[ args!
{
Page 21
int i(
string str(
bool b(
KillThese?alues(out i5 out str5 out b!(
Console"#rite$ine(%int is: {)*%5 i!(
Console"#rite$ine(%String is: {)*%5 str!(
Console"#rite$ine(%Gool is :{)*%5 b!(
Console".ea'$ine(!(
*
*
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 A/erage(params int[ /alues!
{
int sum 2 )(
for (int i 2 )( i 3 /alues"$ength( i44!
sum 2 sum 4 /alues[i(
return (sum - /alues"$ength!(
*
static /oi' Main(string[ args!
{
--pass int /alues in comma separate' form
int a/erage(
a/erage 2 A/erage(@)5 A)5 I)!(
Console"#rite$ine(%The a/erage is: {)*%5 a/erage!(
Page 22
--Pass an array of int
int[ 'ata 2{ @)5 A)5 I) *(
a/erage2A/erage('ata!(
Console"#rite$ine(%The a/earge of the int array ele:{)*%5a/erage!(
Console".ea'$ine(!(
*
*
7utput:
The a/erage is: AJ
The a/earge of the int array ele:AJ
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
Page 23
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
bools and structs are value types.
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 ShapeCnfo
{
public string infoString(
public ShapeCnfo(string info!
{
infoString 2 info(
*
*
struct My.ectangle
{
--The My.ectangle structure conatins a reference type member
public ShapeCnfo rectCnfo(
public int top5 left5 bottom5 right( -- /alue types
public My.ectangle(string info!
{
rectCnfo 2 ne& ShapeCnfo(info!(
top 2 left 2 8)(
bottom 2 right 2 8))(
*
*
class program
{
public static /oi' Main(string[ args!
{
--create the first My.ectangle
Console"#rite$ine(%NOCreating r8%!(
My.ectangle r8 2ne& My.ectangle(%This is my first rect%!(
--no& assign a ne& My.ectangle to r8
Console"#rite$ine(%NOAssigning r9 to r8%!(
My.ectangle r9(
r92r8(
--changing /alues of r9 Console"#rite$ine(%N
OChanging /alues of r9%!(
r9"rectCnfo"infoString2%This is ne& info%(
r9"bottom2A)))(
Page 2
--print /alues
Console"#rite$ine(%NO?alues after change%!( Console"#rite$ine(%N
Or8"rectCnfo"infoString :{)*%5r8"rectCnfo"infoString!( Console"#rite$ine(%N
Or9"rectCnfo"infoString :{)*%5r9"rectCnfo"infoString!(
Console"#rite$ine(%NOr8"bottom:{)*%5r8"bottom!(
Console"#rite$ine(%NOr9"bottom :{)*%5r9"bottom!(
Console".ea'$ine(!(
*
*
7utput:
NOCreating r8
NOAssigning r9 to r8
NOChanging /alues of r9
NO?alues after change
NOr8"rectCnfo"infoString :This is ne&
info NOr9"rectCnfo"infoString :This is
ne& info NOr8"bottom:8))
NOr9"bottom :A)))
Passing Reference Types by Value:
using System(
class person
{
public string fullDame(
public int age(
public person(! { *
public person(string n5 int a!
{
fullDame 2 n(
age 2 a(
*
public /oi' printCnfo(!
{
Console"#rite$ine(%{)* is {8* years ol'%5 fullDame5 age!(
*
*
class program
{
public static /oi' Sen'APersonGy?alue(person p!
{
--change the age of p
p"age 2 FF(
Page 2!
--&ill the caller see this reassignment p
2 ne& person(%ni++i%5 9E!(
*
public static /oi' Main(string[ args!
{
--passing reference types by /alue
Console"#rite$ine(%000000passing person ob,ect by /alue00000000%!(
person smith 2 ne& person(%smith%5 8)!(
Console"#rite$ine(%Gefore by /alue call5 person is:%!(
smith"printCnfo(!(
Sen'APersonGy?alue(smith!(
Console"#rite$ine(%After by /alue call5 person is:%!(
smith"printCnfo(!(
Console".ea'$ine(!(
*
*
7utput:
000000passing person ob,ect by /alue00000000
Gefore by /alue call5 person is:
smith is 8) years ol'
After by /alue call5 person
is: smith is FF years ol'
Passing Reference Types by Reference:
using System(
class person
{
public string fullDame(
public int age(
public person(! { *
public person(string n5 int a!
{
fullDame 2 n(
age 2 a(
*
public /oi' printCnfo(!
{
Console"#rite$ine(%{)* is {8* years ol'%5 fullDame5 age!(
*
*
Page 2"
class program
{
public static /oi' Sen'APersonGy.eference(ref person p!
{
--change the age of p
p"age 2 FF(
--&ill the caller see this reassignment p
2 ne& person(%ni++i%5 9E!(
*
public static /oi' Main(string[ args!
{
--passing reference types by /alue
Console"#rite$ine(%000000passing person ob,ect by
reference00000000%!(
person smith 2 ne& person(%smith%5 8)!(
Console"#rite$ine(%Gefore by ref call5 person is:%!(
smith"printCnfo(!(
Sen'APersonGy.eference(ref smith!(
Console"#rite$ine(%After by ref call5 person is:%!(
smith"printCnfo(!(
Console".ea'$ine(!(
*
*
7utput:
000000passing person ob,ect by reference00000000
Gefore by ref call5 person is:
smith is 8) years ol'
After by ref call5 person is:
ni++i is 9E years ol'
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.
Page 2$
Converting value type to reference type is called boxing by storing the variable in a
System"7b,ect"
Converting reference type to value type to called unboxing
The following example shows both boxing and unboxing:
class Test
{
Public static /oi' Main(!
{
int i28(
ob,ect o 2 i( --bo1ing int
,2(int! o( --unbo1ing
*
*
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 /oi' Main(string[ args!
{
Cnt@9 18 2 8)(
ob,ect o8 2 18( -- Cmplicit bo1ing
Console"#rite$ine(%The 7b,ect o8 2 {)*%5 o8!( -- prints out 8)
--NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
Cnt@9 19 2 8)(
ob,ect o9 2 (ob,ect!19( -- :1plicit Go1ing
Console"#rite$ine(%The ob,ect o9 2 {)*%5 o9!( -- prints out 8)
Console".ea'$ine(!(
*
*
Output:
Page 3%
The Object o1 = 10
The object o2 = 10
Unboxing Custom Value Types:
using System(
struct Mypoint
{
public int 15 y(
*
class program
{
--compiler error5 since to access the fiel' 'ata of Mypoint5 you
must --first unbo1 the parameter" This is 'one in the follo&ing metho'"
-0static /oi' ;seGo1e'Mypoint(ob,ect o!
{
Console"#rite$ine(P{)*5{8**Q5o"15o"y!(
*0-
static /oi' ;seGo1e'Mypoint(ob,ect o!
{
if (o is Mypoint!
{
Mypoint p 2 (Mypoint!o(
Console"#rite$ine(%{)*5{8*%5 p"15 p"y!(
*
else
Console"#rite$ine(%Rou 'i' not sen' a Mypoint%!(
*
public static /oi' Main(string[ args!
{
Mypoint p(
p"1 2 8)(
p"y 2 9)(
;seGo1e'Mypoint(p!(
Console".ea'$ine(!(
*
*
7utput:
8)59)
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:
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.
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 specifed enumeration that has the specifed value.
GetValues() Returns the members of the enumeration.
Property Name
IsDefned()
Description
Returns whether a given string name is a member of the current
enumeration.
using System(
enum :mpType
{
Manager5 -- 2 )
Srunt5 -- 2 8
Contractor5 -- 2 9
?P -- 2 @
*
class program
{
public static /oi' Main(string[ args!
{
--print information for the :mpType enumeration"
Array ob, 2 :num"Set?alues(typeof(:mpType!!(
Console"#rite$ine(%This enum has {)* members:%5 ob,"$ength!(
foreach (:mpType e in ob,!
{
Console"#rite$ine(%String name: {)*%5 e"ToString(!!(
Console"#rite$ine(%int: ({)*!%5 :num"Kormat(typeof(:mpType!5 e5 %=%!!(
Console"#rite$ine(%he1: ({)*!%5 :num"Kormat(typeof(:mpType!5 e5 %L%!!(
*
Console".ea'$ine(!(
*
*
Output:
This enum has 4 members:
String name: Manager
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 :mpType
{
Manager5 -- 2 )
Srunt5 -- 2 8
Contractor5 -- 2 9
?P -- 2 @
*
class program
{
public static /oi' Main(string[ args!
{
--=oes :mpType ha/e a SalesPerson /alueT
if(:num"Cs=efine'(typeof(:mpType!5 %SalesPerson%!!
Console"#rite$ine(%Res &e ha/e sales people%!(
else
Console"#rite$ine(%no sales people%!(
Console".ea'$ine(!(
*
*
7utput:
no sales people
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
public virtual bool Equals(object ob)
whether the object is the same as the one referred
to by ob.
public static bool Equals(object ob1,whether ob1 is the same as ob2.
Page 35
object ob2)
protected Finalize()
Performs shutdown actions prior to garbage
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 /oi' Main(!
{
7b,ect ob,8 2 ne& 7b,ect(!(
7b,ect ob,9 2 ne& 7b,ect(!(
Console"#rite$ine(ob,8":Uuals(ob,9!!(
ob,8 2 ob,9(
Console"#rite$ine(ob,8":Uuals(ob,9!!(
*
*
The output is
Kalse
True
The following example demonstrates the System.Object.Equals(System.Object) method.
using System(
public class MyClass {
public static /oi' Main(! {
string s8 2 %Tom%(
string s9 2 %Carol%(
Console"#rite$ine(%7b,ect":Uuals(<%{)*<%5 <%{8*<%! 2O {9*%5
s85 s95 7b,ect":Uuals(s85 s9!!(
s8 2 %Tom%(
Page 3
s9 2 %Tom%(
Console"#rite$ine(%7b,ect":Uuals(<%{)*<%5 <%{8*<%! 2O {9*%5
s85 s95 7b,ect":Uuals(s85 s9!!(
*
*
The output is
7b,ect":Uuals(%Tom%5 %Carol%! 2O Kalse
7b,ect":Uuals(%Tom%5 %Tom%! 2O True
4efault 5eha"ior of System.6*.ect0
using System(
public class :mployee
{
public string firstDame(
public string lastDame(
public :mployee(string firstDame5 string lastDame!
{
this"firstDame 2 firstDame(
this"lastDame 2 lastDame(
*
public /oi' =isplay(!
{
Console"#rite$ine(%firstDame 2 % 4 firstDame!(
Console"#rite$ine(%lastDame 2 % 4 lastDame!(
*
*
class MainClass
{
public static /oi' Main(!
{
Console"#rite$ine(%Creating :mployee ob,ects%!(
:mployee my:mployee 2 ne& :mployee(%A%5 %M%!(
:mployee my7ther:mployee 2 ne& :mployee(%G%5 %D%!(
Console"#rite$ine(%my:mployee 'etails:%!(
my:mployee"=isplay(!(
Console"#rite$ine(%my7ther:mployee 'etails:%!(
my7ther:mployee"=isplay(!(
Console"#rite$ine(%my:mployee"ToString(! 2 % 4 my:mployee"ToString(!!(
Console"#rite$ine(%my:mployee"SetType(! 2 % 4 my:mployee"SetType(!!(
Console"#rite$ine(%my:mployee"SetHashCo'e(! 2 % 4
my:mployee"SetHashCo'e(!!(
Page 3!
Console"#rite$ine(%:mployee":Uuals(my:mployee5 my7ther:mployee! 2 % 4
:mployee":Uuals(my:mployee5 my7ther:mployee!!(
Console"#rite$ine(%:mployee".eference:Uuals(my:mployee5
my7ther:mployee! 2 % 4 :mployee".eference:Uuals(my:mployee5
my7ther:mployee!!(
Console".ea'$ine(!(
*
*
7utput:
Creating :mployee ob,ects
my:mployee 'etails:
firstDame 2 A
lastDame 2 M
my7ther:mployee 'etails:
firstDame 2 G
lastDame 2 D
my:mployee"ToString(! 2 :mployee
my:mployee"SetType(! 2 :mployee
my:mployee"SetHashCo'e(! 2 AEJE@JIA :mployee":Uuals(my:mployee5
my7ther:mployee! 2 Kalse :mployee".eference:Uuals(my:mployee5
my7ther:mployee! 2 Kalse
Overriding Some Default Behaviors of System.Object:
using System(
using System"Te1t(
class Person
{
public Person(string fname5 string lname5 string ssn5 byte a!
{
KirstDame 2 fname(
$astDame 2 lname(
SSD 2 ssn(
age 2 a(
*
public string KirstDame(
public string $astDame(
public string SSD( public
byte age(
public o/erri'e bool :Uuals(ob,ect o!--7/erri'ing System"7b,ect":Uuals(!
Page 3"
{
Person temp 2 (Person!o(
if(temp"KirstDame 22 this"KirstDame VV
temp"$astDame 22 this"$astDame VV
temp"SSD 22 this"SSD VV
temp"age 22 this"age!
{
return true(
*
else
return false(
*
public o/erri'e string ToString(!--7/erri'ing System"7b,ect"Tostring(!
{
StringGuil'er sb 2 ne& StringGuil'er(!(
sb"Appen'Kormat(%[KirstDame2 {)*%5 this"KirstDame!(
sb"Appen'Kormat(% $astDame2 {)*%5 this"$astDame!(
sb"Appen'Kormat(% SSD2 {)*%5 this"SSD!(
sb"Appen'Kormat(% Age2 {)*%5 this"age!(
return sb"ToString(!(
*
public o/erri'e int SetHashCo'e(!--7/erri'ing System"7b,ect"SetHashCo'e(!
{
return SSD"SetHashCo'e(!(
*
*
--Testing the o/erri'en Members
class MainClass
{
public static /oi' Main(string[ args!
{
Person p8 2 ne& Person(%A%5 %G%5 %999N99N9999%5 FH!(
Person p9 2 ne& Person(%A%5 %G%5 %999N99N9999%5 FH!(
Console"#rite$ine(%Hash co'e of p82{)*%5 p8"SetHashCo'e(!!(
Console"#rite$ine(%Hash co'e of p92{)*%5 p9"SetHashCo'e(!!(
Console"#rite$ine(%String of p82{)*%5 p8"ToString(!!(
Console"#rite$ine(%String of p92{)*%5 p9"ToString(!!(
if (p8":Uuals(p9!!
Console"#rite$ine(%NOp8 an' p9 ha/e same state%!(
else
Console"#rite$ine(%NO p8 an' p9 ha/e 'iffrent state%!(
Console"#rite$ine(%P@ an' PA ha/e same state: {)*%5 ob,ect":Uuals(p85 p9!!(
Console".ea'$ine(!(
*
*
7utput:
Page
39
Hash co'e of p82N8JJ@H))@JA
Hash co'e of p92N8JJ@H))@JA
String of p82[KirstDame2 A $astDame2 G SSD2 999N99N9999 Age2 FH
String of p92[KirstDame2 A $astDame2 G SSD2 999N99N9999 Age2 FH
NOp8 an' p9 ha/e same state
P@ an' PA ha/e same state: True
!ote0 Dee' to reference System"Te1t to access StringGuil'er type"
.NET Array Types:
In C#, an array index starts at zero. That means, first item of an array will be stored at 0
th
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
Page 4%
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 /oi' PrintArrays(int[ MyCnt!
{
Console"#rite$ine(%The int array is%!(
for (int i 2 )( i 3 MyCnt"$ength( i44!
Console"#rite$ine(MyCnt[i!(
*
static string[ SetStringArray(!
{
string[ TheStrings 2 { %Hello%5 %#hat%5 %That%5 %stringarray% *(
return TheStrings(--return a string array
*
public static /oi' Main(string[ args!
{
int[ ages 2{ 8)5 9)5 @)5 A) *(
PrintArrays(ages!( --passing an array as parameter
string[ strs 2 SetStringArray(!( --.ecei/ing a string array in a /ar strs
Console"#rite$ine(%The string array is%!(
foreach (string s in strs!
Console"#rite$ine(s!(
Console".ea'$ine(!(
Page 41
*
*
Output:
&#e int arra' is
1%
2%
3%
4%
&#e string arra' is
(ello
)#at
&#at
stringarra'
Working with Multidimensional Arrays:
using System(
class program
{
public static /oi' Main(string[ args!
{
--A rectangular M= array
int[5 a(
a 2 ne& int[@5 @(
--populate (@0@! array"
for (int i 2 )( i 3@ ( i44! for
(int , 2 )( , 3@( ,44!
a[i5 , 2 i 0 ,(
--print (@0@! array
for (int i 2 )( i 3@( i44!
{
for (int , 2 )( , 3@( ,44!
{
Console"#rite(a[i5 , 4 %<t%!(
*
Console"#rite$ine(!(
*
Console".ea'$ine(!(
*
Page 42
*
% % %
% 1 2
% 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.
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 /oi' Main(string[ args!
{
--Array of string
string[ names 2 { %amir%5 %sharu+%5 %salman%5 %Hrithi+% *(
--print the names
Console"#rite$ine(%<nDames are%!(
for(int i2)(i3names"$ength(i44!
Console"#rite$ine(%{)*%5names[i!(
--copy source array(names! to 'estination array(str!
string[ str 2 ne& string[E(
Array"Copy(names5 str5 A!(
Console"#rite$ine(%<nAfter copy the ne& name array is%!(
for (int i 2 )( i 3 str"$ength( i44!
Console"#rite$ine(%{)*%5 str[i!(
--print the sorte' array
Array"Sort(names!(
Console"#rite$ine(%<nAfter sorting array is%!(
for (int i 2 )( i 3 names"$ength( i44!
Console"#rite$ine(%{)*%5 names[i!(
--.e/erse name array an' print it
Array".e/erse(names!(
Console"#rite$ine(%<nThe re/erse array %!(
for(int i2)(i3names"$ength(i44!
Console"#rite$ine(%{)*%5names[i!(
--clear out all e1cept hrithi+
Array"Clear(names585@!(
Console"#rite$ine(%<nclear out all e1cept hrithi+%!(
for(int i2)(i3names"$ength(i44!
Console"#rite$ine(%{)*%5names[i!(
System"Console".ea'$ine(!(
*
Page 44
*
7utput:
Dames are
amir
sharu+
salman
Hrithi+
After copy the ne& name array
is amir
sharu+
salman
Hrithi+
After sorting array
is amir
Hrithi+
salman
sharu+
The re/erse
array sharu+
salman
Hrithi+
amir
clear out all e1cept hrithi+
sharu+
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 /oi' cir'isp(!
{
Console"#rite$ine(@"8A 0 9 0 9!(
*
*
public class Triangle
{
public /oi' tri'isp(!
{
Console"#rite$ine()"E 0 9 0 9!(
*
*
public class .ectangle
{
public /oi' rec'isp(!
{
Console"#rite$ine(9 0 9!(
Page 4
*
*
*
using System(
using MyShapes(
class Class8
{
public static /oi' Main(!
{
circle c 2 ne& circle(!(
Triangle t 2 ne& Triangle(!(
.ectangle r 2 ne& .ectangle(!(
c"cir'isp(!(
t"tri'isp(!(
r"rec'isp(!(
Console".ea'$ine(!(
*
*
Output
Creating Nested namespace:
namespace *oo+s
,
namespace -nventor'
,
using .'stem/ class
0dd-nventor'
,
pu1lic void 2'2et#od34
,
Console5)rite6ine370dding -nventor' via 2'2et#od874/
9
9
9
9
Page 4!
using *oo+s/
class (ello)orld
,
pu1lic static void 2ain34
,
-nventor'50dd-nventor' 0dd-nv : ne; 0dd-nventor'34/
0dd-nv52'2et#od34/
9
9
output:
0dding -nventor' via 2'2et#od
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
libraries5
Page 4"

Vous aimerez peut-être aussi