1. Structure in C Sharp
A struct is a simple user-defined type, a lightweight alternative to a class. The structure in C# can
contain fields, methods, constants, constructors, properties, indexers, operators and even other
structure types.
Structures are very similar to classes in C#, but with following properties
1. A struct is useful for creating types that are used to hold data like Point, Rectangle, Color
types.
2. A C# structure is a value type and the instances or objects of a structure are created in stack.
3. A struct may contain constructors, fields, method, and properties.
4. A struct can implement interface.
5. Struct can neither inherit by another class, nor can they be inherited.
Structure Declaration
The keyword struct can be used to declare a structure. The general form of a structure declaration in
C# is as follows.
<modifiers> struct <struct_name>
{
//structure member
}
Where the modifier can be private, public, internal or public. The struct is the required keyword.
For example
struct MyStruct
{
public int x;
public int y;
}
Structure object creation
The objects of a strcut can be created by using the new operator as follows.
MyStruct ms = new MyStruct
The individual members of a struct can be accessed by using the dot (.) operator as showing below.
ms.x=10;
ms.y=20;
Program on Structure
using System;
struct MyStruct
{
public int x;
public int y;
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.x = 10;
ms.y = 20;
int sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}
2. Write a program to create 3 child thread.
class MyThread
{
public int count;
public Thread thrd;
public MyThread(string name)
{
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// Entry point of thread.
void run()
{
Console.WriteLine(thrd.Name + " starting.");
while (count < 10)
{
Thread.Sleep(500);
Console.WriteLine("In " + thrd.Name + ", count is " + count);
count++;
}
Console.WriteLine(thrd.Name + " terminating.");
}
}
public class MoreThreads
{
public static void Main()
{
// Construct three threads.
MyThread mt1 = new MyThread("Child 1");
MyThread mt2 = new MyThread("Child 2");
MyThread mt3 = new MyThread("Child 3");
}
}
Output:-
Child 1 starting.
Child 2 starting.
Child 3 starting.
In child 1, cout is 0
In child 2, cout is 0
In child 3, cout is 0
In child 1, cout is 1
In child 2, cout is 1
In child 3, cout is 1
In child 1, cout is 2
Child 1 is terminating.
In child 2, cout is 2
Child 2 is terminating.
In child 3, cout is 2
Child 3 is terminating.