C#: The Language-II

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.



Structures

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



Classes

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.
eg. 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 : gaurav.aroraose@yahoo.co.in*/

// 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.Clear();
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);
Console.ReadLine();

}
static void Main()
{
//Create an object of class
enroll objEnroll = new enroll();
objEnroll.getInfo();
objEnroll.showInfo();
}
}
}


Displaying C# Class


Access Modifiers

Modifiers

Description

Private

Only members of class have access

Protected

All members in current class and in derived classes have access to the elements

Internal

Only members in current project have access to the elements

Protected Internal

Only members in current project and all members in derived class can access the variables

Public

All members have access in all lasses and projects

 


Move to Home Page Move to Previous Page Move to Page#1 Move to Last Page#4

C#: The Language-II

Constructors and Destructors

A constructor is a method, which is called when an object of a class type is constructed, and it usually used for initialization. A constructor method has following characteristics:

Note: You can declare private constructors also, when you don’t want to allow client to directly handle your class.

CDCode: The example of private constructor is shown in file privateconstructor.cs

In example privateconstructor.cs tells that the private constructors are not accessible outside the class or in other words private constructors are important to use when you don’t provide the accessibility to the client of the class.


Static Constructors

Static constructors are automatically initialize when class initializes, we can directly use the class members without creating the instance of that class [see static construtor].

Static Constructor


In the other hand a Destructor is also called a finalizer. It is just opposite the constructor, it is a method called when the garbage collector reclaims an object.

Constructors have following characteristics:



Similarities in Class and Structure



Differences in Class and Structure


Move to Home Page Move to Previous Page Move to Page#2 Move to Last Page

C#: The Language-II

Inheritance

A Class inherits the members of its direct base class. Inheritance means that a class contains all members of its direct class, except for the constructors and destructors of the base class.

Importance of inheritance

Important:When you inherit a class private variables of base class also get inherited, but these can not access directly by the class interface.

For more detail check code Inheritance in action

Inheritance in Action

Note:In above example, there are declared private variable(s) also, but these are not accessible outside the class. Try yourself to rewrite the code and taste the feature if inheritance.



Interface

An interface is simply a collection of function prototypes. An Interface is a reference type like a class, but interface can contain only abstract members. In other words, Interface is a contract that defines the signature of the functionality.

An interface looks like a class definitions, but its only purpose is to define a set of methods and not to implement them. For this reason the interface definition includes only the definition of methods [in other words the abstract methods]. Interface contains only methods, properties and delegates but can not contain fields, constructors, destructor and any type of static members.

Note:All members in Interface are public. While inheriting an Interface, we have to implement all the members defined in the interface. This is the main difference between inheriting a class and an interface.

Important:C# does not support multiple inheritances, but we can attain the same with the help of Interfaces. Also, Interface members are Public by default but private in case of Class.

For more detail check code Interface in action

Inheritance in Action



Virtual Method(s)

A virtual method is which one declared with virtual keyword. This method has overridden in the base class.

Important:
1. Virtual keyword signifies that method(s) and properties, defined, can be overridden.
2. You can stop abstract class to override by supplying sealed keyword. Also in same way abstract methods are also not to be overridden.

For more detail how to implement overriding check code: Virtual Method

Note:
1. When override a virtual function in a derived class, use ‘override’ keyword, which signals that virtual function is being overridden.
2. The ability to call objects of derived classes through base reference and get the correct method executed at runtime is called polymorphism.

Virtual Method



Hiding Method(s)

A Hiding method is just like virtual method. When methods is declared with the same signature in both base and derived class without the use of virtual and override keyword(s), the concept is called Hiding method. You can attain the hiding with using new keyword in the derived class.

Note:Method hiding is also possible without use of new keyword, but it sends the compilation warning.

CDCode:The example of method hiding is shown in file methodhiding.cs.

Method Hiding



Difference in Overriding and Hiding

There are following difference(s):


Move to Home Page Move to Previous Page Move to Page#3 Move to Last Page

C#: The Language-II

Abstract Classes and Abstract Method(s)

The abstract classes a design concept, which means they cannot implement directly and meant only to be as base classes. You cannot create an instance of abstract class:

Characteristics of Abstract Class

 

In the other hand, abstract methods are virtual method which are implemented and sign in derived or inherited class. Abstract methods are only defined in abstract class but implementation is done only in the derived class. As these are virtual, declaring without the keyword virtual but these are implemented using override keyword in derived class.

The Code snippet Implementing Abstract Class described the complete view of Abstract class and Abstract method.

Abstract Class and Abstract Method

Difference between abstract classes and interfaces


Move to Home Page Move to Previous Page Move to Page#4 Move to Last Page

C#: The Language-II

Properties

Properties provide a useful way to handle access to data members.

A property is a member that provides access to an attribute of an object or a class. Like color of the car etc. Properties are natural extension of fields.  Both are named members with associated types, and the syntax of accessing fields and properties is the same.

Properties are defined with property declaration, using get accessor and set accessor.

Note: Supply only get accessor when property is readonly and set if it is writeonly.



The Code snippet describes the use of properties.

Implementing C#:Properties



Indexers

Indexers are an elaboration of properties, and are used where we want to access some class property by index, in an array-like manner. They are useful in cases when a class is a container for other objects. Indexers are declared using this [] keyword.

Important: An indexer is a member that enables an object to be indexed in the same way as an array. In C# there are no static indexers.



The Code snippet describes the use of Indexers.

Implementing C#:Properties



Delegates

Delegates are similar to interfaces but they provide a template for a single method rather than a number of related methods, as is common with interfaces. A delegate defines a function without implementing it, and another class provides an implementation. Delegates are similar to function pointers in C++ and the main difference is that C# delegates are much safer than function pointers due to their type safety.

In other words, delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and it can only reference those methods whose signature is compliant with the class. Delegates are type safe function pointers.



The Code snippet describes the use of Delegates.

Implementing C#:Delegates



Events

In C# events are based on delegates, with the originator defining one or more call back functions. A call back function is a function in which one piece of code defines another implements, in other words, one piece of code says, “If you implement a function which looks like this, I can call it”. A class that wants to sue events defines callback functions or delegates, and the listening object then implements them.

An event is a member that enables an object or class to provide notifications.

As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source. Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.

Important: Events have no return type.



The Code snippet describes the use of Events.

Implementing C#:Events

Difference between Delegates and Events


Move to Home Page Move to Previous Page Move to Next Page Move to Last Page