Wednesday, 16 February 2011

Chapter 10 Object & Classes in C# Part I

C# is a powerful Object Oriented programming language. Lets first look at some basics of OOPs then we will see how C# implements it.

What are Objects ?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your bicycle, you yourself, your car etc.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Cars also have state (current gear, current speed) and behavior (changing gear, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Observe the real-world objects. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Write down your observations.You'll notice that real-world objects vary in complexity; your table fan may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your cell phone radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world object, they consist of state and related behavior. An object stores its state in variables and exposes its behavior through methods/functions. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.


By attributing state (speed, current gear,fuel) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the car has 4 gears, a method to change gears could reject any value that is less than 1 or greater than 4.
Bundling code into individual software objects provides a number of benefits, including:

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

What is a Class ?

Many individual objects belong to the same family. There may be thousands of cars in existence, all of the same make and model. Each car was built from the same set of blueprints and therefore contains the same kind of machinery. In OOPs terminology, we can say that our vehicle is an instance of the class of objects known as CARS. A class is the blueprint from which individual objects are created.

What Is Inheritance?


Different kinds of objects often have a certain amount in common with each other. SUV's, Sports Cars and Family cars, for example, all share the characteristics of cars (speed, fuel,heat, gear). Yet each also defines additional features that make them different: SUV's are four wheel drive; sports car have more powerful engine and smaller size; family cars have more space and more safety features with lower speed.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Car becomes the superclass of SUV's, SportsCar, and FamilyCar.


What is Polymorphism ?

Poly means many. morph mens to change. There fore polymorphism is a concept of OOPs under which a variable, function, or an object can have more than one meaning within the program.
If we try to define it a bit more technically "polymorphism is the ability to hide alternative implementations behind a common interface. This concept leverages inheritance and encapsulation among other OO concepts.Polymorphism is the ability for objects of different types to respond to messages of the same type. The concept behind polymorphism is that a function or data type can be written in a generic way, so that it can handle any interactions to it regardless of the acting object’s type."
This can be sub-divided in two broad categories Compile-time and Run-time polymorphism. we will look into this more deeply in the next few sections given below.

C# implementation of OOPs

Objects in C#(MS guidlines)


  1. Everything you use in C# is an object, including Windows Forms and controls.
  2. Objects are instantiated; that is, they are created from templates defined by classes and structs.
  3. Objects use Properties/State to obtain and change the information they contain.
  4. Objects often have methods and events that allow them to perform actions.
  5. Visual Studio provides tools for manipulating objects: the Properties Window allows you to change the attributes of objects such as Windows Forms. The Object Browser allows you to examine the contents of an object.
  6. All C# objects inherit from the Object.

Classes in C#


Following is the syntax to create a simple class in C#, you have already seen the basic syntax earlier in our sample programs, because everything in C# is an object or sub-class.
public class Student
{
    //Fields, properties, methods and events go here...
}
Now if you want to use this class you must create an object and following are the methods to do so.
Student obj=new Student();
Note the usage of new operator, if you do not use this then the program will fail at run time.
Student obj1=new Student();
 Student obj2=obj1;
In the above example we have created an object called obj1 and then another object called obj2, which refers to obj1, thus any change in obj2 will be like changing obj1 itself. Because objects are of reference type.(Do not confuse them with pointers)

Fields

Fields are part of class which hold class data, We have referred it to as state in our earlier discussion. They give the class the ability to store values which may be used to define the state of an object. Microsoft advises us to declare all the fields as private and use methods or properties to modify them but for simplicity sake we will define them as public in our sample program.
using System;
/**
 * author         Sudeep Mukherjee
 * description    Basic program to declare fields in C# class and use 
 *                 them to take some input and then print it
 * */
namespace MySamples
{
    class Student
    {
        public string name;
        public int age;
        public float hindi, english, maths;
    }

    class RunSample
    {
        static void Main(string[] args)
        {
            Student obj1 = new Student();
            Console.Write("Enter students name ");
            obj1.name=Console.ReadLine();

            Console.WriteLine("Student name is {0}", obj1.name);

        }
    }
}


Properties

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
using System;

/**
 * author         Sudeep Mukherjee
 * description     Basic program to declare fields and properties 
 *                 in C# class and use them to take some input and 
 *                 then print it
 * */
namespace MySamples
{
    class Student
    {
        public string name;
        private int age;
        public float hindi, english, maths;
        public int studentage {
            get { return age; }
            set
            {
                if (value < 0 || value >= 100)
                {
                    age = 1;
                }
                else
                {
                    age = value;
                }
            }
        }

    }

    class RunSample
    {
        static void Main(string[] args)
        {
            Student obj1 = new Student();
            Console.Write("Enter students name ");
            obj1.name=Console.ReadLine();
            Console.Write("Enter students age ");
            obj1.studentage=int.Parse(Console.ReadLine());
            Console.WriteLine("Student name is {0} and his age is {1}", obj1.name,obj1.studentage);
            Console.ReadKey(false);

        }
    }
}


Sample Output


In the program above I have declared one private field, age and one property, studentage which checks if the age given is between the permitted range of 1 to 100, if it is not then the field is given a value of 1.
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.
The value keyword is used to define the value being assigned by the set indexer.
Properties that do not implement a set method are read only.

Methods

Methods define the actions that a class can perform. Method can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter.A method is a code block containing a series of statements. In C#, every executed instruction is done so in the context of a method. Methods are declared within a class by specifying the access level, the return value, the name of the method, and any method parameters. Method parameters are surrounded by parentheses, and separated by commas. Empty parentheses indicate that the method requires no parameters.
using System;
/**
 * author         Sudeep Mukherjee
 * description     Basic program to declare fields,properties and methods
 *                 in C# class and use them to take some input and 
 *                 then print it
 * */
namespace MySamples
{
    class Student
    {
        public string name;
        private int age;
        public float hindi, english, maths;
        public int studentage {
            get { return age; }
            set
            {
                if (value < 0 || value >= 100)
                {
                    age = 1;
                }
                else
                {
                    age = value;
                }
            }
        }
        public bool IsEligible() {
            bool answer = false;
            if (studentage > 14 && studentage < 17)
                answer = true;
            else
                answer = false;
            return answer;
        }

    }

    class RunSample
    {
        static void Main(string[] args)
        {
            Student obj1 = new Student();
            Console.Write("Enter students name ");
            obj1.name=Console.ReadLine();
            Console.Write("Enter students age ");
            obj1.studentage=int.Parse(Console.ReadLine());
            if(obj1.IsEligible())
                Console.WriteLine("Student {0} is elligible because his age is {1}", obj1.name,obj1.studentage);
            else
                Console.WriteLine("Student {0} is not elligible because his age is {1}", obj1.name, obj1.studentage);
            Console.ReadKey(false);

        }
    }
}
In this example a method IsEligible is a member of Student class and returns true if the student is of correct age to sit this exam( arbitrary condition)or false if he/she is overage or under age. Last point I would like to discuss in this chapter is Call by value and call by reference To illustrate my point I will show you two methods and the difference between the two
using System;
/**
 * author         Sudeep Mukherjee
 * description     Basic program to show the difference in call by value
 *                 and call by reference
 * */
namespace MySamples
{
    class Student
    {
        public string name;
        private int age;
        public float hindi, english, maths;
        public int studentage {
            get { return age; }
            set
            {
                if (value < 0 || value >= 100)
                {
                    age = 1;
                }
                else
                {
                    age = value;
                }
            }
        }
        public bool IsEligible() {
            bool answer = false;
            if (studentage > 14 && studentage < 17)
                answer = true;
            else
                answer = false;
            return answer;
        }
        public void valueTypeCall(int val)
        {
            val = 312;
        }

        public void referenceTypeCall(Student val)
        {
            val.studentage = 29;
        }

    }

    class RunSample
    {
        static void Main(string[] args)
        {
            Student obj1 = new Student();
            int i = 40;
            obj1.valueTypeCall(i);
            Console.WriteLine("value of i is {0}",i);
            Student obj2 = new Student();
            obj2.studentage = 11;
            obj1.referenceTypeCall(obj2);
            Console.WriteLine("value of studentage is {0}", obj2.studentage);

            Console.ReadKey(false);

        }
    }
}

Sample Output


In the first instance I send a variable 'i' to a function, where the value of this variable is changed. We expect that the change should be visible in the main function but that is not the case why? because value of the variable is copied into a new local variable , thus any changes made inside the function will not be affect the copy.
On the other hand the next function passes the object by reference thus any changes made inside the function will reflect on the original object and in the main function too.

Next chapter will deal with more OOPS based parts of C#.

No comments:

Post a Comment