Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, May 6, 2011

Interacting via the Command-Line



Interacting via the Command-Line

Besides command-line input, another way to provide input to a program is via the Console. Typically, it works like this: You prompt the user for some input, they type something in and press the Enter key, and you read their input and take some action. Listing 1-3 shows how to obtain interactive input from the user.
Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs
// Namespace Declarationusing System; // Program start classclass InteractiveWelcome {     // Main begins program execution.    public static void Main()     {         // Write to console/get input        Console.Write("What is your name?: ");         Console.Write("Hello, {0}! ", Console.ReadLine());         Console.WriteLine("Welcome to the Mahe's Home page!");     } }
In Listing 1-3, the Main method doesn't have any parameters -- mostly because it isn't necessary this time. Notice also that I prefixed the Main method declaration with the publickeyword. The public keyword means that any class outside of this one can access that class member. For Main, it doesn't matter because your code would never call Main, but as you go through this tutorial, you'll see how you can create classes with members that must be public so they can be used. The default access is private, which means that only members inside of the same class can access it. Keywords such as public and private are referred to as access modifiers. Lesson 19 discusses access modifiers in more depth.
There are three statements inside of Main and the first two are different from the third. They are Console.Write(...) instead of Console.WriteLine(...). The difference is that theConsole.Write(...) statement writes to the console and stops on the same line, but the Console.WriteLine(...) goes to the next line after writing to the console.
The first statement simply writes "What is your name?: " to the console.
The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the formatted string is Console.ReadLine().  This causes the program to wait for user input at the console. After the user types input, their name in this case, they must press the Enter key. The return value from this method replaces the "{0}" parameter of the formatted string and is written to the console. This line could have also been written like this:
string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);

The last statement writes to the console as described earlier. Upon execution of the command-line with "InteractiveWelcome", the output will be as follows:
>What is your Name?  [Enter Key] >Hello, !  Welcome to the C# Mahe !

Thursday, May 5, 2011

Getting Started with C#


This lesson will get you started with C# by introducing a few very simple programs. Here are the objectives of this lesson:




  • Understand the basic structure of a C# program.
  • Obtain a basic familiarization of what a "Namespace" is.
  • Obtain a basic understanding of what a Class is.
  • Learn what a Main method does.
  • Learn how to obtain command-line input.
  • Learn about console input/output (I/O).
A Simple C# Program
There are basic elements that all C# executable programs have and that's what we'll concentrate on for this first lesson, starting off with a simple C# program. After reviewing the code in Listing 1-1, I'll explain the basic concepts that will follow for all C# programs we will write throughout this tutorial. Please see Listing 1-1 to view this first program.
Warning: C# is case-sensitive.

Listing 1-1. A Simple Welcome Program: Welcome.cs
// Namespace Declaration
using
 System;

// Program start class
class WelcomeCSS
{    // Main begins program execution.    static void Main()
    {        // Write to console        Console.WriteLine("Welcome to the C# Station Tutorial!");
    }
}
The program in Listing 1-1 has 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. It can be compiled with the following command line:
csc.exe Welcome.cs
This produces a file named Welcome.exe, which can then be executed. Other programs can be compiled similarly by substituting their file name instead of Welcome.cs. For more help about command line options, type "csc -help" on the command line. The file name and the class name can be totally different.
Note for VS.NET Users: The screen will run and close quickly when launching this program from Visual Studio .NET. To prevent this, add the following code as the last line in the Main method:
// keep screen from going away
// when run from VS.NET

Console.ReadLine();


Thursday, January 20, 2011

Monday, January 10, 2011

Campus placements: students have no choice?



students have no choice?

   It is that time of the year when young men and women, clad in formals, sit outside offices on their college campus revising their much-rehearsed answers to anticipated questions on technology and applications.
The campus recruitment drive this year, especially by Information Technology companies, which started as early as in the first week of December has been encouraging, say the placement records of many engineering colleges. However, the recruitment processes of many colleges that involve bulk recruitment by a single company are conspicuous by the absence of other major companies.
With the placement scenario increasingly governed by unspoken alliances between companies and colleges, the freedom of a student to pick a company from a basket of choices could be under threat, say experts.
The Campus Placement at SRM University saw Tata Consultancy Services (TCS) roping in a whopping 1,091 students last month, with Wipro, HCL, and Accenture following suit. But it was also marked by the absence of two other top-notch companies. Similarly VIT University had Cognizant taking in as many as 1,500 students with other companies recruiting in smaller numbers.
‘The best harvest’
While companies maintain that they insist on the first slot only to get ‘the best harvest,’ colleges say that it has become mandatory to show 100 per cent placement, and bulk recruitment by IT majors is a boon for their healthy branding and survival.
“It is natural for colleges to lose out on two to three main companies, because they give the first slot to one big player,” says. S. Ganapathy, dean, SRM Placements. Some of these bulk recruiters also relaxed their eligibility criteria by allowing students with up to two arrears.
NASSCOM regional director K. Purushottaman does not see anything wrong with the phenomenon since students can choose not to be part of the campus recruitment, and make a start with smaller companies or apply in companies that don’t come for recruitment, if they want to.
Infosys HRD and Education and Research head T.V. Mohandas Pai, on the other hand, says the lack of transparency on the part of college managements sometimes leads to abuse of the tie-ups between companies and colleges. “Many colleges succumb to pressures from certain companies, and get into unhealthy tie-ups with companies that leave students with little choice,” he says.
Others point out that latent contracts and invisible ties between management authorities of private colleges and HR professionals of companies result in companies dictating terms to the college. “Since colleges are responsible only till the students are placed, companies with their rigorous training, demand-driven strategies, posting and transfer mechanisms make sure that the people who do not perform are removed whenever necessary,” says Anand Venkatesh, a HR placement consultant with many IT majors.
For students, these tie-ups and placements in previous batches largely determine a certain college’s worth. “But we often feel that a large part of the recruitment process is kept hidden from us, all we know are numbers,” says Abhishek Tareja, a civil engineering student of VIT University.
What MoUs mean
There are also those who argue that agreements between corporate players and the academia must not be seen through the prism of placements alone. The Memorandums of Understanding signed between companies and universities reflect in infrastructure development, faculty enhancement programmes, capacity building, projects and internships, says S. Selvam, Director, Centre for University- Industry Collaboration, Anna University, which saw 88 companies recruiting candidates in 92 working days. “Placements are just a spin-off from these regular programmes, but unfortunately they figure at the top of the list for many colleges,” he adds.
It is also the relationship a particular company shares with a certain college that determines their association. “Most colleges give us their first slots willingly because we managed to recruit even during the downturn. It is that rapport that counts,” says R. Chandrasekharan, President and MD, Global Delivery, Cognizant.
Time-bound associations between companies and colleges, Dr. Selvam says, are an indirect, invisible investment for the future. They not only save cost for the companies, but also help them groom their candidates for future, while the branding works well both for the college and the employer, say experts. This could prove crucial at a time when, according to Mr Pai, the expenditure on training is rising with increasing costs of technology, infrastructure, and compensation.
Many academics also insist that traditional tie-ups fostered by colleges with companies wherein students are granted projects and internships depending on the prototype or design they submit, are what that go a long way in kindling the spirit of engineering in them. “Students look forward to such associations because it gives them an opportunity to work in real-time projects and showcase their potential to gain employment in companies that normally do not come to their campuses for placement,” Praveen Vishakantaiah, President, Intel India, who also believes that such recruitments are often overshadowed by the bulk recruitment that IT majors indulge in.

Job fair on Jan 12



http://mahendran-mahe.blogspot.com-Job_fair
        
   A job fair for recruiting manpower for private sector enterprises under the aegis of Tamil Nadu Corporation for Development of Women Ltd will be organised here on January 12.
In a press release here today, District Collector Mahesan Kasirajan said the job fair, to be organised in the SGSY Hall in Collectorate premises, will be for the aspirants from the districts of Tiruchirapalli, Ariyalur, Perambalur, Karur, Nagapattinam and Pudukottai.
Candidates in the age group of 18 to 35 years can take part.
Aspirants should furnish their bio-data and documents pertaining to age, residential proof at the camp. Further information can be obtained from the Project Officer of Mahalir Thittam, he added.

Sunday, January 9, 2011

It’s raining IT jobs



Mahendran

  Software companies are on a hiring spree, as the IT industry, after a few years of sluggishness, is back in robust growth mode.
It is as if the software industry is on a hiring binge. Students from private universities are being recruited in thousands. First, Tata Consultancy Services (TCS) recruited 1,091 from SRM University where 2,023 students were placed in software leaders including TCS, Wipro and HCL, in just seven days. Next, Cognizant Technology Solutions (CTS) handed over job offers to 1,643 students of VIT University, Vellore.
At SASTRA University, Thanjavur, as on date, over 1,800 job offers have been made with TCS, creating a new record. TCS recruited 1,359 SASTRA students during its three-day campus recruitment drive early this month, says V. Badrinath, Dean – Training & Placements. Over 30 companies have visited the campus till now.
“The university is also formalising various post-recruitment activities in consultation with the recruiters to utilise the last semester in the most productive form. This will make the graduates readily employable by the industry and also address the growing concern of students’ academic interest after securing a job,” says S. Vaidhyasubramaniam, Dean – Planning & Development, SASTRA University.
In Madurai, TCS has selected 618 students from Thiagarajar College of Engineering (TCE). It is not just the ECE, CSC & IT, EEE graduates are getting placed. Students of bio-medical engineering, bio-informatics and other disciplines, with aptitude and communication skills, are being picked up by the IT industry in droves.
After a few years of sluggishness, the IT industry is on a robust growth path. “There is a pent-up demand,” says Lakshmi Narayanan, vice-chairman, Cognizant. “In the last one year (October 2009 to September 2010), we saw a net addition of over 27,500 employees. On December, we crossed the 1 lakh employee mark, says Sriram Rajagopal, vice-president, HR, Cognizant.
Software professionals say that the projects are lined up from January next year and the demand has hit a high again with companies luring programmers with lucrative packages as a result of which the attrition rate has also been quite high everywhere. Employees are asked to refer candidates on a weekly basis.
Significantly, this is the first batch of students, after the State scrapped the entrance test for engineering admissions, being placed now. “Even the students who studied in Tamil medium in Plus Two are placed in good numbers. It is the basic subject knowledge that matters most,” says G.K. Rajesh, placement officer, TCE.
In Tiruchi, Anna University of Technology – Tiruchi (AUT-T) and Bharathidasan University are viewing the job market with cautious optimism. Recruiters enlisted for conducting job interviews at the AUT-T during the course of this year constitute an equal mix of manufacturing and IT/ITES sector.
According to M. Jayakumar, director, Department of Extension and Career Guidance, Bharathiar University, the university was not able to place more than 300 students last year. “This year, as of now there is a 30 per cent improvement. Many more drives are in the pipeline.” Companies showing interest in placements (in arts and science) this year are from banking, insurance, customer support services, infrastructure and financial services. K.P. Dhanabalakrishnan, placement officer, Dr. Mahalingam College of Engineering and Technology, Pollachi, says that at the first placement drive the college conducted, nearly 300 students got placed in four companies.
“In the IT field, Pondicherry University has already achieved 100 per cent placements this year,” says S.K.V. Jayakumar, the head of placements. Mass recruiters such as TCS, Cognizant and Accenture select the candidates first and then include them in projects once they join. Small recruiters on the other hand make project-specific selections.
“This year we have come out of a slowdown. Recruitment is expected to be high, since the growth projection of the industry seems good in the coming year. We plan to recruit from at least 25 engineering colleges in Tamil Nadu in the next month,” says V. Viswanathan, talent acquisition team, WIPRO.
For science graduates, Wipro has a special PG programme called Wipro Academy of Software Excellence in BITS Pilani, after which the students will be employed in the company. “This year we are looking at providing admissions to at least 5,000 students under this programme. The percentage of science graduates recruited every year is around 5 to 8 percentage. In the subsequent two or three years we must try and translate this into 15 to 20 percentage,” says Mr. Viswanthan.

Wednesday, January 5, 2011

Key Concepts of Object Orientation



Abstract Classes:

Abstract classes are a special type of base classes. In addition to normal class members, they have abstract class members. These Abstract class members are methods and properties that are declared without an implementation. All classes derived directly from abstract classes must implement all of these abstract methods and properties.
Abstract classes can never be instantiated. This would be illogical, because of the members without implementations. So what good is a class that can't be instantiated? Lots! Abstract classes sit toward the top of a class hierarchy. They establish structure and meaning to code. They make frameworks easier to build. This is possible because abstract classes have information and behavior common to all derived classes in a framework. Take a look at the following example:
abstract public class Contact // Abstract Class Contact.
{
protected string name;
public Contact()
{
// statements...
}
public abstract void generateReport();
abstract public string Name
{
get;
set;
}
}

Contact, is an abstract class. Contact has two abstract members, and it has an abstract method named generateReport(). This method is declared with the abstract modifier in front of the method declaration. It has no implementation (no braces) and is terminated with a semicolon. The Name property is also declared abstract. The accessors of properties are terminated with semicolons.
public class Customer : Contact // Customer Inherits Abstract Class Contact.
{
string gender;
decimal income;
int numberOfVisits;
public Customer()
{
// statements
}
public override void generateReport()
{
// unique report
}
public override string Name
{
get
{
numberOfVisits++;
return name;
}
set
{
name = value;
numberOfVisits = 0;
}
}
}
public class SiteOwner : Contact
{
int siteHits;
string mySite;
public SiteOwner()
{
// statements
}
public override void generateReport()
{
// unique report
}
public override string Name
{
get
{
siteHits++;
return name;
}
set
{
name = value;
siteHits = 0;
}
}
}

The abstract base class Contact has two derived classes, Customer and SiteOwner. Both of these derived classes implement the abstract members of the Contact class. The generateReport() method in each derived class has an override modifier in its declaration. Likewise, the Name declaration contains an override modifier in both Customer and SiteOwner.
C# requires explicit declaration of intent when overriding methods. This feature promotes safe code by avoiding the accidental overriding of base class methods, which is what actually does happen in other languages. Leaving out the override modifier generates an error. Similarly, adding a new modifier also generates an error. Abstract methods must be overridden and cannot be hidden, which the new modifier or the lack of a modifier would be trying to do.
The most famous of all abstract classes is the Object class. It may be referred to as object or Object, but it's still the same class. Object is the base class for all other classes in C#. It's also the default base class when a base class is not specified. The following class declarations produce the same exact results:

abstract public class Contact : Object
{
// class members
}
abstract public class Contact
{
// class members
}

Object is implicitly included as a base class if it is not already declared. Besides providing the abstract glue to hold together the C# class framework, object includes built-in functionality, some of which is useful for derived classes to implement.

Tuesday, January 4, 2011

Key Concepts of Object Orientation



Calling Base Class Members:

Derived classes can access the members of their base class if those members have protected or greater access. Simply use the member name in the appropriate context, just as if that member were a part of the derived class itself. Here's an example:
abstract public class Contact
{
private string address;
private string city;
private string state;
private string zip;
public string FullAddress()
{
string fullAddress = address + '\n' + city + ',' + state + ' ' + zip;
return fullAddress;
}
}
public class Customer : Contact
{
public string GenerateReport()
{
string fullAddress = FullAddress();
// do some other stuff...
return fullAddress;
}
}

In above example, the GenerateReport() method of the Customer class calls the FullAddress() method in its base class, Contact. All classes have full access to their own members without qualification. Qualification refers to using a class name with the dot operator to access a class member-MyObject.SomeMethod(), for instance. This shows that a derived class can access its base class members in the same manner as its own.
More Tips regarding Inheritance:

    * A static member cannot be marked as override, virtual, or abstract. So following is an error:
      public static virtual void GetSSN()
    * You can't call static methods of base class from derived class using base keyword.
      In above example if you declare a static method as follows:


public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public static void GetInfo()
{
// Implementation
}
}
now you can't call this method using base.GetInfo() from derived class instead you have to call Person.GetInfo() from derived class.
Inside Static members we can access only static fields, methods etc.
Following example will give error, because we can't access name in GetInfo() because name is not static.

public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public static void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}

Virtual or abstract members cannot be private.

    *  If you are not overriding a virtual method of base class in derived class, you can't use base class method by using base keyword in derived class. Also when you will create an instance of derived class, it will call derived class method and you will only be able to access base class method when you will create instance of base class.
    * You can't decrease access level of a method in derived class when you are overriding a base class method in derived class, vice versa is possible.
      Means you can make protected method of base class to public in derived class.


The "this" keyword refers to:

    * the current instance for which a method is called. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
      The following are common uses of this:

To qualify members hidden by similar names, for example: 

public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}

In above example, this.name refers to private variable name in the class. If we write name = name, then this will refer to argument name of the constructor Employee and not to private variable name in the class. In this case private variable name will never be initialized.

    * To pass an object as a parameter to other methods, for example:
      CalcTax(this);



To declare indexers, for example:

public int this [int param]
{
get
{
return array[param];
}
set
{
array[param] = value;
}
}

It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.
In this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar names. It is also used to pass an object to the method CalcTax, which belongs to another class.
// keywords_this.cs
// this example
using System;
public class Employee
{
public string name;
public string alias;
public decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
}
public class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:
Employee E1 = new Employee ("John M. Trainer", "jtrainer");
// Display results:
E1.printEmployee();
}
}

Monday, January 3, 2011

Key Concepts of Object Orientation



Access Keywords

base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.

The base keyword is used to access members of the base class from within a derived class:
Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance method, or an instance property accessor.
In following example, both the base class, Person, and the derived class, Employee, have a method named Getinfo. By using the base keyword, it is possible to call the Getinfo method on the base class, from within the derived class.
// Accessing base class members

using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}

abstract public class Contact
{
private string address;
public Contact(string b_address)
{
this.address = b_address;
}
}
public class Customer : Contact
{
public Customer(string c_address) : base(C_address)
{
}
}

In this code, the Customer class does not have an address, so it passes the parameter to its base class constructor by adding a colon and the base keyword with the parameter to its declaration. This calls the Contact constructor with the address parameter, where the address field in Contact is initialized.
One more example which shows how base-class constructor is called when creating instances of a derived class:

using System;
public class MyBase
{
int num;
public MyBase()
{
Console.WriteLine("In MyBase()");
}
public MyBase(int i)
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived : MyBase
{
static int i = 32;
// This constructor will call MyBase.MyBase()
public MyDerived(int ii) : base()
{
}
// This constructor will call MyBase.MyBase(int i)
public MyDerived() : base(i)
{
}
public static void Main()
{
MyDerived md = new MyDerived(); // calls public MyDerived() : base(i) and
// passes i=32 in base class
MyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)
}
}

Output
in MyBase(int i)
in MyBase()
The following example will not compile. It illustrates the effects of not including a default constructor in a class definition:

abstract public class Contact
{
private string address;
public Contact(string address)
{
this.address = address;
}
}
public class Customer : Contact
{
public Customer(string address)
{
}
}

In this example, the Customer constructor does not call the base class constructor. This is obviously a bug, since the address field will never be initialized.
When a class has no explicit constructor, the system assigns a default constructor. The default constructor automatically calls a default or parameterless base constructor. Here's an example of automatic default constructor generation that would occur for the preceding example:
 
public Customer() : Contact()
{
}

When a class does not declare any constructors, the code in this example is automatically generated. The default base class constructor is called implicitly when no derived class constructors are defined. Once a derived class constructor is defined, whether or not it has parameters, a default constructor will not be automatically defined, as the preceding code showed.

Sunday, January 2, 2011

Key Concepts of Object Orientation



Implementation or Behavior

The code inside of a method is called the implementation. Sometimes it is also called behavior since it is this code that actually makes the object do useful work.

Client applications can use our object even if we change the implementation-as long as we don't change the interface. As long as our method name and its parameter list and return data type remain unchanged, we can change the implementation all we want.
So Method Signature depends on:

    * Method name
    * Data types of parameters
    * Either Parameter is passed ByVal or ByRef.
    * Return type of method.


It is important to keep in mind that encapsulation is a syntactic tool-it allows our code to continue to run without change. However, it is not semantic-meaning that, just because our code continues to run, doesn't mean it continues to do what we actually wanted it to do.
Member or Instance Variables
The third key part of an object is its data, or state. Every instance of a class is absolutely identical in terms of its interface and its implementation-the only thing that can vary at all is the data contained within that particular object.
Member variables are those declared so that they are available to all code within our class. Typically member variables are Private in scope-available only to the code in our class itself. They are also sometimes referred to as instance variables or as attributes. The .NET Framework also refers to them as fields.
We shouldn't confuse instance variables with properties. A Property is a type of method that is geared around retrieving and setting values, while an instance variable is a variable within the class that may hold the value exposed by a Property.

Interface looks like a class, but has no implementation.

The only thing it contains is definitions of events, indexers, methods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined. So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will. Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.
Because interfaces must be defined by inheriting classes and structs, they define a contract. For instance, if class foo inherits from the IDisposable interface, it is making a statement that it guarantees it has the Dispose() method, which is the only member of the IDisposable interface. Any code that wishes to use class foo may check to see if class foo inherits IDisposable. When the answer is true, then the code knows that it can call foo.Dispose().
Defining an Interface: MyInterface.c

interface IMyInterface
{
void MethodToImplement();
}

Above listing shows defines an interface named IMyInterface. A common naming convention is to prefix all interface names with a capital "I", but this is not mandatory. This interface has a single method named MethodToImplement(). This could have been any type of method declaration with different parameters and return types. Notice that this method does not have an implementation (instructions between curly braces- {}), but instead ends with a semi-colon, ";". This is because the interface only specifies the signature of methods that an inheriting class or struct must implement.
All the methods of Interface are public by default and no access modifiers (like private, public) are allowed with any method of Interface.
Using an Interface: InterfaceImplementer.cs

class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}

The Interface Implementer class in above listing implements the IMyInterface interface. Indicating that a class inherits an interface is the same as inheriting a class. In this case, the following syntax is used:

Class InterfaceImplementer : IMyInterface
Note that this class inherits the IMyInterface interface; it must implement its all members. While implementing interface methods all those needs to be declared public only. It does this by implementing the MethodToImplement() method. Notice that this method implementation has the exact same signature, parameters and method name, as defined in the IMyInterface interface. Any difference will cause a compiler error. Interfaces may also inherit other interfaces. Following listing shows how inherited interfaces are implemented.
Interface Inheritance: InterfaceInheritance.cs

using System;
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}

The code in above listing contains two interfaces: IMyInterface and the interface it inherits, IParentInterface. When one interface inherits another, any implementing class or struct must implement every interface member in the entire inheritance chain. Since the InterfaceImplementer class in above listing inherits from IMyInterface, it also inherits IParentInterface. Therefore, the InterfaceImplementer class must implement the MethodToImplement() method specified in the IMyInterface interface and the ParentInterfaceMethod() method specified in the IParentInterface interface.

In summary, you can implement an interface and use it in a class. Interfaces may also be inherited by other interface. Any class or struct that inherits an interface must also implement all members in the entire interface inheritance chain.

Inheritance is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects.
Inheritance is the ability to apply another class's interface and code to your own class.
Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base class members marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Inheriting base class members in derived class is not mandatory.

Saturday, January 1, 2011

Key Concepts of Object Orientation



Key Concepts of Object Orientation

    * Abstraction
    * Encapsulation
    * Polymorphism
    * Inheritance.

Abstraction is the ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions.
Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type.
Examples:
    * You can create an abstraction of a dog with characteristics, such as color, height, and weight, and actions such as run and bite. The characteristics are called properties, and the actions are called methods.
    * A Recordset object is an abstract representation of a set of data.

Classes are blueprints for Object.
Objects are instance of classes.


C# Example of Class:public class Draw
{// Class code.}

Object References When we work with an object we are using a reference to that object. On the other hand, when we are working with simple data types such as Integer, we are working with the actual value rather than a reference.
When we create a new object using the New keyword, we store a reference to that object in a variable. For instance:
Draw MyDraw = new Draw;
This code creates a new instance of Draw. We gain access to this new object via the MyDraw variable. This variable holds a reference to the object.

Now we have a second variable, which also has a reference to that same object. We can use either variable interchangeably, since they both reference the exact same object. The thing we need to remember is that the variable we have is not the object itself but, rather, is just a reference or pointer to the object itself.

Early binding means that our code directly interacts with the object, by directly calling its methods. Since the compiler knows the object's data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our development efforts; it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values.

Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn't care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn't known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get unprecedented flexibility in exchange.

If we enable strict type checking by using Option Strict On at the top of our code modules, then the IDE and compiler will enforce early binding behavior. By default, Option Strict is turned off and so we have easy access to the use of late binding within our code.

Access Modifiers Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

Public is visible to everyone. A public member can be accessed using an instance of a class, by a class's internal code, and by any descendants of a class.
 

Private is hidden and usable only by the class itself. No code using a class instance can access a private member directly and neither can a descendant class.






















Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.






















Internal/Friend is public to the entire application but private to any outside applications. Internal is useful when you want to allow a class to be used by other applications but reserve special functionality for the application that contains the class. Internal is used by C# and Friend by VB .NET.


Protected Internal may be accessed only by a descendant class that's contained in the same application as its base class. You use protected internal in situations where you want to deny access to parts of a class functionality to any descendant classes found in other applications.


 
Composition of an OBJECT

We use an interface to get access to an object's data and behavior. The object's data and behaviors are contained within the object, so a client application can treat the object like a black box accessible only through its interface. This is a key object-oriented concept called Encapsulation. The idea is that any programs that make use of this object won't have direct access to the behaviors or data-but rather those programs must make use of our object's interface.
There are three main parts of Object:
1. Interface
2. Implementation or Behavior
3. Member or Instance variables
 

Interface  
The interface is defined as a set of methods (Sub and Function routines), properties (Property routines), events, and fields (variables or attributes) that are declared Public in scope.

Thursday, December 30, 2010

Key Concepts of Object Orientation



Difference between Interface and Abstract Class:

    * Interfaces are closely related to abstract classes that have all members abstract.
    * For an abstract class, at least one method of the class must be an abstract method that means it may have concrete methods.
    *  For an interface, all the methods must be abstract
    * Class that implements an interface much provide concrete implementation of all the methods definition in an interface or else must be declare an abstract class
    * In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class can only be derived once.
    * An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
    * Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
    * Class members that implement the interface members must be publicly accessible.

Monday, December 27, 2010

Add the Glitter Effect Mouse Pointer to your Site



The code for this tweak is javascript. All you need to do is to add the javascript code to your template but only within the head () tag


script type="text/javascript">
// starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";

rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="2px";
rlef.style.left="0px";

rdow.style.top="0px";
rdow.style.left="2px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;

oy=y;
for (c=0; c
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";

starv[c]=50;
break;
}
}
for (c=0; c
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";

if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";

starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";

star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
}
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";

}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {

tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;

x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {

sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;

sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;

shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {

swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";

div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>