Escolar Documentos
Profissional Documentos
Cultura Documentos
enumeration, delegate).Unlike C(++), it is not possible to create global functions or global points of data.
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.
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:
using System;
classHelloClass
{
public static int Main(string[] args)
{
Console.WriteLine("***** Command line args *****");
Console.WriteLine("Hello World!");
return 0;
}
}
// Notice we have no need to check the size of the array when using
//'foreach'.
OutPut:
using System;
class program
{
static void Main(string[] args)
{
string s1, s2;
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:
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();
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.
using System;
class helloclass
{
public string usermessage;
public helloclass()
{
Console.WriteLine("\n\nDefault Constr called");
}
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
C# constructors are named identical to the class they are constructing, and do not take a
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");
}
Output:
inside static construtor...
Test2
inside regular construtor... i=4
inside regular construtor... i=4
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........
Principal among the methods of System.Console are Read( ), ReadLine( ) Write( ) and
WriteLine( ), all of which are defined as static.
return 0;
}
}
Output:
OutPut:
int is: 90
Double is: 9.99
Bool is : True
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.
Example:
using System;
class helloclass
{
Console.ReadLine();
return 0;
}
}
Output:
C format: $99,989.99
using System;
class someclass
{
//Accessible anywhere.
public void publicmethod()
{
Console.WriteLine("Visiblity of member is public");
}
//ASsembly-protected access
protectedinternal void protectedinternalmethod()
{
Console.WriteLine("Visiblity of member is protectedinternal");
}
class helloclass
{
//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
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
class program
{
public int myInt=9;
Public string myString="hello";
Public bool myBool=true;
Public object myObj=99.999;
Output:
class ConstData
{
public conststring BestStudentTeam = "7 th ise";
public constdouble SimplePI = 3.14;
public constbool Truth = true;
}
class program
{
Console.ReadLine();
}
}
Output:
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;
}
}
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.
[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:
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.
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.
// 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.
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.
.
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.
class Program
{
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";
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”.
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
class Program
{
Output:
int is: 10
Bool is :True
using System;
class Program
{
int average;
average = Average(30, 40, 70);
Output:
The average is: 46
The avearge of the int array ele:46
• Another distinction between value and reference type is that a value type is derived from System.ValueT
from System.Object.
using System;
class ShapeInfo
{
public string infoString;
public ShapeInfo(string info)
{
infoString = info;
}
}
struct MyRectangle
{
//The MyRectangle structure conatins a reference type member
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");
//changing values of r2
Console.WriteLine("->Changing values of r2");
r2.rectInfo.infoString="This is new info";
r2.bottom=4000;
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
class person
{
public string fullName;
public int age;
public person() { }
class program
{
public static void SendAPersonByValue(person p)
{
//change the age of p
p.age = 99;
SendAPersonByValue(smith);
Console.WriteLine("After by value call, person is:");
smith.printInfo();
Console.ReadLine();
}
}
Output:
class person
{
public string fullName;
public int age;
public person() { }
public person(string n, int a)
{
fullName = n;
age = a;
}
SendAPersonByReference(ref smith);
Console.WriteLine("After by ref call, person is:");
smith.printInfo();
Console.ReadLine();
}
}
Output:
class Test
{
Public static void Main()
{
int i=1;
object o = i; //boxing
int j=(int) o; //unboxing
}
}
• 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
{
Output:
else
Console.WriteLine("You did not send a Mypoint");
}
Output:
10,20
An enum is a value type with a set of related named constants often referred to as an
enumerator list.
Example:
Note: In C#, the numering scheme sets the first element to zero {0} by default, followed by an
n+1 progression.
enum EmpType
{
Manager = 102, // = 0
Grunt, // = 103
Contractor, // = 104
VP // = 105
}
This base class defines a number of methods(mentioned in the following table) that allow you
to integrate and transform a given enumeration.
GetName() Retrieves a name (or an array containing all names) for the
GetNames() constant in the specified enumeration that has the specified value.
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);
Console.ReadLine();
}
}
Output:
This enum has 4 members:
hex: (00000000)
int: (1)
hex: (00000001)
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
namespace System
public Object();
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.
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
s1 = "Tom";
The output is
using System;
class MainClass
{
Console.WriteLine("myEmployee details:");
myEmployee.Display();
Console.WriteLine("myOtherEmployee details:");
myOtherEmployee.Display();
Console.WriteLine("Employee.ReferenceEquals(myEmployee,
myOtherEmployee) = " + Employee.ReferenceEquals(myEmployee,
myOtherEmployee));
Console.ReadLine();
Output:
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;
}
return sb.ToString();
}
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);
if (p1.Equals(p2))
Console.WriteLine("->p1 and p2 have same state");
else
Console.WriteLine("-> p1 and p2 have diffrent state");
Output:
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.
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
int [] intArray;
intArray = new int[3] {0, 1, 2};
You can even direct assign these values without using the new operator.
string[] strArray = {"Ronnie", "Jack", "Lori", "Max", "Tricky"};
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]);
}
Console.ReadLine();
10
20
30
40
Hello
What
That
stringarray
using System;
class program
{
Console.WriteLine();
}
Console.ReadLine();
}
0 0 0
0 1 2
0 2 4
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.
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.
Write C# program to demonstrate the methods of Array class i,e copy, sort, reverse, and clear
using System;
class program
{
System.Console.ReadLine();
}
Output:
Names are
amir
sharuk
salman
Hrithik
amir
sharuk
salman
Hrithik
amir
Hrithik
salman
sharuk
sharuk
salman
Hrithik
amir
sharuk
int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} };
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);
}
}
}
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
namespace Books
{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}
}
}
}
output:
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.