0% found this document useful (0 votes)
49 views33 pages

Establishing Member Visibility:: Using Class

The document discusses the differences between value types and reference types in C#. It explains that value types include numerical data types and structs, which are allocated on the stack. Reference types are object references allocated on the heap. When a value type is assigned to another, a member-by-member copy is made, while assigning a reference type only copies the reference. The document also provides an example using a struct containing a reference type to demonstrate that changing the reference type's value through one variable is reflected in the other, since they reference the same object.

Uploaded by

Kumar Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views33 pages

Establishing Member Visibility:: Using Class

The document discusses the differences between value types and reference types in C#. It explains that value types include numerical data types and structs, which are allocated on the stack. Reference types are object references allocated on the heap. When a value type is assigned to another, a member-by-member copy is made, while assigning a reference type only copies the reference. The document also provides an example using a struct containing a reference type to demonstrate that changing the reference type's value through one variable is reflected in the other, since they reference the same object.

Uploaded by

Kumar Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

Establishing Member Visibility:

 Members of a given class or structure must specify their visibility level. If


you define a member without specifying an accessibility keyword, it
automatically defaults to private.

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)


{
someclass c = new
someclass();
c.publicmethod();
c.internalmethod();
c.protectedinternalmetho
d();

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

Console.ReadLine();

return 0;
}
}
Output:

Visiblit of member is public


y of member is interna
Visiblit of member is l
y protectedinternal
Visiblit
y
Establishing Type Visibility

 Classes, interfaces, structures, enumerations and delegates can also take


accessibility modifiers, but are limited to public or internal.
 When you create a public type, you ensure that the type can be accessed
from other types in the current assembly as well as external assemblies.

public class HelloClass { }

 An internal type can be used only by the assembly in which it is defined. If


you create a .NET code library that defines 3 internal types, assemblies
that references the *.dll would not be able to see, create or in any way
interact with them.
 Internal is the default accessibility for the types in C#.

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:
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 const string BestStudentTeam = "7 th ise";
public const double SimplePI = 3.14;
public const bool Truth =
true;
}
Referencing Constant Data:

class program
{

Public const string BestCollege = "EPCET";

static void Main(string[ ]


args)
{
//print constant values defined by other type

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 diferences.

con
st
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

keyword.
 To use a constant outside of the class that it is declared in, you
must fully qualify it using the class name.
readonly
A readonly member is like a constant in that it represents an
unchanging value. The
diference 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 diferent 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. 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.
Understanding the Value Type and References Types
 C# defines a number of keywords that represents basic data types such as
whole numbers, character data, floating point numbers and Boolean value.
 A .NET data type may be value – based or reference – based.
 Value based types include all numerical data types, as well as
enumerations and structures, that are allocated on stack.
 Value types can be quickly removed from memory once they fall out of the
defining scope.
 When you assign one value type to another, a member – by – member copy
is achieved by default.
 .NET structures are value types. Structures can take constructors and
define any number of members. All structures are implicitly derived from a
class named System.ValueType.
 The purpose of System.ValueType is to override the virtual methods
defined by System.Object.
 To allocate a structure type, you must make use of new keyboard. When
the runtime encounters a type derived from System.ValueType, stack
allocation is achieved.
 References types are allocated on managed heap. These objects stay in
memory until the .NET garbage collector destroys them.
 By default, assignment of reference types results in a new reference to the
same object on the heap.
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;
//print values

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


Console.WriteLine("->r1.rectInfo.infoString
:
{0}",r1.rectInfo.infoStr
ing);
Console.WriteLine("->r2.rectInfo.infoString
:
{0}",r2.rectInfo.infoStri
ng);
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 2
->Values after change
->r1.rectInfo.infoString
->r2.rectInfo.infoString
->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;//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();
}
}
Outpu
t:

******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);
}
}
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

Difference between value type and reference type


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.

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=123;

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:
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:

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.

Format() )

GetName() Property Name


GetNames(
) IsDefined()

GetValues(
Returns
the string
associated
with the
enumerati
on.

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

Returns
the
members
of the
enumerati
on.

Descripti
on

Returns
whether a
given
string
name is a
member of
the current
enumerati
on.
using System;
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
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

.NET Array Types:

In C#, an array index starts at zero. That means, first item of an array will be stored at
th
0 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 and jagged 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.

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();
}
}
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();
}

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
Rank array.
Returns the number of dimensions of an array.

Table 2 describes some of the Array class methods.

BinarySearc This method searches a one-dimensional sorted Array for a


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

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();
}
}
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

Program for array of Class

public class employee


{
String N,U;
int M;
public employee(String Name , String USN, int marks)
{
N=Name;
U=USN;
M=marks;
}
public void display()
{

Console.WriteLine("Name: {0} USN:{1} Marks {2}",N,U,M);

}
}

public class Array_Class


{
public static void Main()
{
employee[] ob=new employee[5]; //Employee Class Array

ob[0]=new employee("Ram","1AYIS01",300);
ob[1]=new employee("Raj","1AYIS02",400);
ob[2]=new employee("Rock","1AYIS03",500);
ob[3]=new employee("Rana","1AYIS04",600);
ob[4]=new employee("Raki","1AYIS05",700);
for(int i=0;i<5;i++)
{
ob[i]. display();
}
console.ReadLine();

}
}

Working with structures

A structure is a value type like a class, a structure can have its own fields, methods, and
constructors. Because structures are stored on the stack, as long as the structure is reasonably
small, the memory management overhead is often reduced.

Declaring a structure
 To declare own structure type, use the struct keyword followed by the name of the type
and then enclose the body of the structure between opening and closing braces.
Syntactically, the process is similar to declaring a class. For example, here is a structure
named Time that contains three public int fields named hours, minutes, and seconds:
struct Time
{
public int hours, minutes, seconds;
}
 As with classes, making the fields of a structure public is not advisable in most cases;
there is no way to control the values held in public fields. For example, anyone could set
the value of minutes or seconds to a value greater than 60.
 A better idea is to make the fields private and provide your structure with constructors
and methods to initialize and manipulate these fields, as shown in this example:
struct Time
{
private int hours, minutes, seconds;
...
public Time(int hh, int mm, int ss)
{
this.hours = hh % 24;
this.minutes = mm % 60;
this.seconds = ss % 60;
}
public int Hours()
{
return this.hours;
}
}
When you copy a value type variable, you get two copies of the value. In contrast, when
you copy a reference type variable, you get two references to the same object.

Understanding differences between structures and classes


 A structure and a class are syntactically similar, but they have a few important differences
 Let’s look at some of these variances: We can’t declare a default constructor (a constructor
with no parameters) for a structure. The following example would compile if Time were a
class, but because Time is a structure it does not:
struct Time
{
public Time() { ... } // compile-time error
...
}
 The reason we can’t declare your own default constructor for a structure because the
compiler always generates one.
 In a class, the compiler generates the default constructor only if you don’t write a constructor
yourself.
 The compiler-generated default constructor for a structure always sets the fields to 0, false, or
null—just as for a class. Therefore, we should ensure that a structure value created by the
default constructor behaves logically and makes sense with these default values.
 We can initialize fields to different values by providing a nondefault constructor. However,
nondefault constructor must explicitly initialize all fields in structure; the default
initialization no longer occurs. If you fail to do this, you’ll get a compile-time error. For
example, although the following example would compile and silently initialize seconds to
0 if Time were a class, it fails to compile because Time is a structure:
struct Time
{private int hours, minutes, seconds;
public Time(int hh, int mm)
{
this.hours = hh;
this.minutes = mm;
} // compile-time error: seconds not initialized
}
 In a class, you can initialize instance fields at their point of declaration. In a structure, you
cannot. The following example would compile if Time were a class, but it causes a compile-
time error because Time is a structure:
struct Time
{
private int hours = 0; // compile-time error
private int minutes;
private int seconds;
}
 The following table summarizes the main differences between a structure and a class
For example:
struct Time
{
private int hours, minutes, seconds;
...
public Time(int hh, int mm)
{
hours = hh;
minutes = mm;
seconds = 0;
}
}

Program illustrating structures and enumerations: Write a C# program to design a structure


Student<USN, Name, Marks, Branch>. Here, Branch is of type Enum with members
MCA, MBA, MTech. Add appropriate constructor and also a method to hike the marks
by 10% to only MCA students. Show creation of some Student objects and the way to
call these methods.
using System;
public enum Branch
{
MCA, MBA, MTech
}
struct Student
{
string USN;
string Name;
double marks;
Branch b;
public Student(string usn, string name, double m, Branch br)
{
USN=usn;
Name=name;
marks=m;
b=br;
}

public void Hike_Marks()


{
if(b==Branch.MCA)
{
marks=marks + 0.1 * marks;
}

public void disp()


{
Console.WriteLine("{0} \t {1} \t\t {2} \t\t {3}", USN, Name, marks, b);
}
}
Class Sample
{
public static void Main()
{
Student[] s=new Student[4];
s[0]=new Student("1RN07MCA01","Abhishek",75.0,Branch.MCA);
s[1]=new Student("1RN07MCA55","Ramu",78.0,Branch.MCA);
s[2]=new Student("1RN06MBA01","Shamu",72.0,Branch.MBA);
s[3]=new Student("1RN08MTec01","Rani",75.0,Branch.MTech);

for(int i=0;i<4;i++)
s[i].Hike_Marks();

Console.WriteLine("***********Student Details *************");


Console.WriteLine("USN \t \tName \t\t Marks \t\t Branch");
for(int i=0;i<4;i++)
s[i].disp();
}
}

You might also like