0% found this document useful (0 votes)
138 views

System Helloworldapplication: Using Namespace

The document contains code for a C# program that prints "Hello World". It defines a Main method in a HelloWorld class within the HelloWorldApplication namespace that writes "Hello World" to the console and waits for user input before exiting. The program uses the System namespace, defines a class with a main method that writes to the console, and pauses the program before closing.
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views

System Helloworldapplication: Using Namespace

The document contains code for a C# program that prints "Hello World". It defines a Main method in a HelloWorld class within the HelloWorldApplication namespace that writes "Hello World" to the console and waits for user input before exiting. The program uses the System namespace, defines a class with a main method that writes to the console, and pauses the program before closing.
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 23

C#

using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.
The next line has the namespace declaration. A namespace is a collection of
classes. The HelloWorldApplication namespace contains the class HelloWorld.

using System;
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}

public double GetArea()


{
return length * width;
}

public void Display()


{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}

class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}

Member Variables
Variables are attributes or data members of a class, used for storing data. In the
preceding

program,

the Rectangle class

has

two

member

variables

namedlength and width.


The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables. object,dynamic, and string.

Pretvaranje vale u object


object obj;
obj = 100; // this is boxing

u vreme izvrsavanja odredjuje tip


dynamic d = 20;
String str = "Tutorials Point";
85
0x4b
30
30u
30l
30ul

/* decimal */
/* hexadecimal */
/* int */
/* unsigned int */
/* long */
/* unsigned long */

Private access specifier allows a class to hide its member variables and member
functions from other functions and objects. Only functions of the same class can access
its private members. Even an instance of a class cannot access its private members.
Protected access specifier allows a child class to access the member variables and
member functions of its base class. This way it helps in implementing inheritance.

Internal Access Specifier


other words, any member with internal access specifier can be accessed from any class
or method defined within the application in which the member is defined.
internal double length;
internal double width;

The Null Coalescing Operator (??)


double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;

nizovi

double[] balance = new double[10];


int [] marks = new int[5] { 99, 98, 92, 97, 95};

int [] n = new int[10]; /* n is an array of 10 integers */


foreach (int j in n ) { }
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

We can define class members as static using the static keyword. When we declare a
member of a class as static, it means no matter how many objects of the class are
created, there is only one copy of the static member.

Nasledjivanje

class Rectangle: Shape

C# does not support multiple inheritance. However, you can use interfaces to
implement multiple inheritance.
polymorphism
The following example shows using function print() to print different data types:
Function overloading
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}

void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}

void print(string s)

{
Console.WriteLine("Printing string: {0}", s);
}

Dynamic Polymorphism
Abstract classes contain abstract methods, which are implemented by the derived
class. The derived classes have more specialized functionality.
When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual functions. The virtual functions could be
implemented differently in different inherited class and the call to these functions will
be decided at runtime.
class Shape
{
protected int width, height;
public Shape( int a=0, int b=0)
{
width = a;
height = b;
}
public virtual int area()
{
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{

}
public override int area ()
{
Console.WriteLine("Rectangle class area :");

return (width * height);


}
}
class Triangle: Shape
{
public Triangle(int a = 0, int b = 0): base(a, b)
{

}
public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}

Operator Overloading
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}

ne moze overload dodela, logicki

interfejsi
public interface ITransactions
{
// interface members

void showTransaction();
double getAmount();
}

public class Transaction : ITransactions


{}

#define PI
MatchCollection mc = Regex.Matches(text, expr); //regularni izrazi

try, catch, finally, and throw.


finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
Catch(Exception e)
{
...
Throw e
}

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);


using System;
using System.IO;

namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite);
for (int i = 1; i <= 20; i++)
{
F.WriteByte((byte)i);
}

F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
}
}
}

-----------------------------------Attributes

AttributeUsage
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

Conditional
public class Myclass
{
[Conditional("DEBUG")]
public static void Message(string msg)
{
Console.WriteLine(msg);
}
}

The parameter iserror, is a Boolean value. If its value is true, the compiler should treat
the use of the item as an error. Default value is false (compiler generates a warning).
public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
static void OldMethod()
{
Console.WriteLine("It is the old method");
}
static void NewMethod()
{
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}

properties
using System;
namespace tutorialspoint
{
class Student
{
private string code = "N.A";
private string name = "not known";
private int age = 0;

// Declare a Code property of type string:


public string Code
{
get

{
return code;
}
set
{
code = value;
}
}

// Declare a Name property of type string:


public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:


public int Age
{
get
{
return age;
}
set
{
age = value;
}
}

public override string ToString()


{
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}
}

property kod apstraktnih klasa


public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}

class Student : Person


{

private string code = "N.A";


private string name = "N.A";
private int age = 0;

// Declare a Code property of type string:


public string Code
{
get
{
return code;

}
set
{
code = value;
}
}

// Declare a Name property of type string:


public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:


public override int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{

return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}
}

An indexer allows an object to be indexed such as an array. When you define an


indexer for a class, this class behaves similar to a virtual array. You can then access
the instance of this class using the array access operator ([ ]).
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}

public string this[int index]


{
get
{
string tmp;

if( index >= 0 && index <= size-1 )


{
tmp = namelist[index];
}
else
{
tmp = "";
}

return ( tmp );
}

set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}

static void Main(string[] args)


{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ )
{
Console.WriteLine(names[i]);
}

Console.ReadKey();
}

A delegate is a reference type variable that holds the reference to a method. The
reference can be changed at runtime.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{

class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects


nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls
the two delegates it was composed from. Only delegates of the same type can be
composed. The "-" operator can be used to remove a component delegate from a
composed delegate.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}

public static int getNum()


{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc;

NumberChanger nc1 = new NumberChanger(AddNum);


NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;

//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

Various Collection Classes and Their Usage


The

following

are

the

various

commonly

used

classes

of

theSystem.Collection namespace. Click the following links to check their detail.

Class

Description and Useage


It represents ordered collection of an object that can beindexed individually.

ArrayLis
t

It is basically an alternative to an array. However, unlike array you can add and remove items
from a list at a specified position using an index and the array resizes itself automatically. It
also allows dynamic memory allocation, adding, searching and sorting items in the list.

It uses a key to access the elements in the collection.


Hashtabl
e

A hash table is used when you need to access elements by using key, and you can identify a
useful key value. Each item in the hash table has a key/value pair. The key is used to access
the items in the collection.

SortedLi

It uses a key as well as an index to access the items in a list.

st
A sorted list is a combination of an array and a hash table. It contains a list of items that can be
accessed using a key or an index. If you access items using an index, it is an ArrayList, and if

you access items using a key , it is a Hashtable. The collection of items is always sorted by the
key value.

It represents a last-in, first out collection of object.


Stack

It is used when you need a last-in, first-out access of items. When you add an item in the list, it
is called pushing the item and when you remove it, it is called popping the item.

It represents a first-in, first out collection of object.


Queue

It is used when you need a first-in, first-out access of items. When you add an item in the list, it
is calledenqueue and when you remove an item, it is calleddeque.

It represents an array of the binary representation using the values 1 and 0.


BitArray

It is used when you need to store the bits but do not know the number of bits in advance. You
can access items from the BitArray collection by using an integer index, which starts from
zero.

Generics allow you to delay the specification of the data type of programming
elements in a class or a method, until it is actually used in the program. In other
words, generics allow you to write a class or method that can work with any data type.
using System;
using System.Collections.Generic;

namespace GenericApplication
{
public class MyGenericArray<T>
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];

public T getItem(int index)


{
return array[index];
}

public void setItem(int index, T value)


{
array[index] = value;
}
}

class Tester
{
static void Main(string[] args)
{

//declaring an int array


MyGenericArray<int> intArray = new MyGenericArray<int>(5);

delegate T NumberChanger<T>(T n);

Anonymous methods
using System;
delegate void NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{

static int num = 10;


public static void AddNum(int p)
{
num += p;
Console.WriteLine("Named Method: {0}", num);
}

public static void MultNum(int q)


{
num *= q;
Console.WriteLine("Named Method: {0}", num);
}

public static int getNum()


{
return num;
}
static void Main(string[] args)
{
//create delegate instances using anonymous method
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};

//calling the delegate using the anonymous method


nc(10);

//instantiating the delegate using the named methods


nc = new NumberChanger(AddNum);

//calling the delegate using the named methods


nc(5);

//instantiating the delegate using another named methods


nc = new NumberChanger(MultNum);

//calling the delegate using the named methods


nc(2);
Console.ReadKey();
}
}
}

You might also like