Sunday, August 10, 2008

Classes and Structures

Lets take these in general words, these are template from which you define object to access their functionalities. The programmers of C++ and Java are well aware from these two names. Till now from above reading you new that Classes are reference type and structures are value type so they are stored on Heap and Stack respectively in memory.

A structure in C# is simply a composite data type [you are well aware from composite data type, refer to data types for more details], which consists number of members of other types. The structure define simply by using the struct keyword

struct enroll
public string name, fname, mname;
public string char sex;
Public int age;
public string address;

Important points towards structures

There are some points towards structures:
1. Structures are C# composite data types
2. By default like classes structures are public
3. Sealed and Abstract modifiers cant applicable on structures
4. Structures have no inheritance features
5. A variable of structure type contains all the data of structure
6. Structures cant allow a destructor
7. By default C# provides a constructor with no parameter, but explicitly you cant use and replace it.
8. Initializations of fields are not allowed.

It is cleared from above study that Classes are reference type. A class is a collection of its data members. Data members are those members of class which contains the data of class like fields, constants and events etc. Class is declared simply just followed by class keyword with optional modifiers; by default C# classes are public.

class myClass
public int xyz;
public string name;
public const int y=22;

In above, all members are public, when we declare members we can optionally supply modifiers, in C# all class members private by default.

/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at :*/
// File name : classstructue.cs
using System;
namespace CSharp.AStepAhead.classstructue
class enroll
string name, fname;
int age;
char sex;
void getInfo()
Console.WriteLine("Enter Name: ");
name = Console.ReadLine();
Console.WriteLine("Enter Father Name: ");
fname = Console.ReadLine();
Console.WriteLine("Enter age: ");
age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Sex [Male -m, Female - f]: ");
sex = char.Parse(Console.ReadLine());
void showInfo()
Console.WriteLine("You have provided following information(s): \n");
Console.WriteLine(" Name : {0}\n Father Name : {1}\n Age : {2}\n Sex : {3}", name, fname, age, sex);
static void Main()
//Create an object of class
enroll objEnroll = new enroll();

No comments:

Post a Comment