Jump to content
xisto Community
turbopowerdmaxsteel

C# Tutorial : Lesson 4 - Object Oriented Programming

Recommended Posts

Object Oriented Programming

 

Object Oriented Programming is a methodology modeled on real life. It comprises of the basic unit, an object, being used in implementing a program. Think of all the objects around you - cars, buses, birds, trees, etc. You will find countless ones of them, everywhere you go. In order to tackle this huge number, we started classifying them, thus came the term Class.

 

Class

A class is a composition of the theoretic characteristics (attributes and properties) of an object and the things it can do - behaviors, methods and features. Take the Car as an example. Its characteristics can include speed, color, number of gears, etc and it exhibits behaviors such as accelerate, brake and gear-change.

 

Posted Image

 

Object

An object is an instance of a class. Consider the Car class above, the Aston Martin that was used in the movie - Die another Day is an object of the car class. One point to note is that each object has at least one attribute that makes it unique.

 

Posted Image

 

Message Passing

Objects do not exist in isolation. They interact with other objects. These interactions take place through messages. Message passing is the process by which an object (sender) sends data to another object (receiver) or asks the other object to invoke a method. Thus, each message has a sender and a receiver.

 

Behavior

It is how an object acts and reacts, in terms of its state changes and message passing. For example, when the driver applies the break, the car comes to a stop.

 

Posted Image

 

This was all about the object oriented methodology. Now, let us take a look on how OOP is used in C#

 

Declaring Classes

We declare classes using the following syntax:-

 

class < Class Name >

{

 

data membersâ¦

 

member functionsâ¦

 

}

 

Here class is a keyword. Class name can be anything that follows the naming rules.

 

Rules for naming classes

A class name must begin with a letter & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)

Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the class name.

A class name must not be the same as a reserved keyword such as using, public, etc.

Conventions for naming classes

Class Name must be meaningful, ideally a noun.

Naming of classes can be done using either the Pascal case, where the first character is capital and the rest are in small letters or using the Camel Case in which the first letter is in small case but the first letter of each successive word is in caps. Example:-

Pascal Case: Classone

Camel Case: classOne

The conventions are not mandatory but best practices, abiding by which allows others to easily understand our code.

 

Data members are the variables or other objects declared inside the class while member functions are the functions declared in it.

 

Example Class:-

 

class Student{	// Data Members	public string Name;	public int Age; 	// Member Function	public void Display()	{		Console.WriteLine("Name {0}\n Age {1}", Name, Age);	}}
The public access specifier has been used in order to allow the data members & functions to be visible from outside the class. The access specifiers will be explained in the forthcoming tutorials.

 

Declaring & Instantiating Objects

Creating objects is similar to declaring variables and can be done using the syntax:-

 

<Class Name> <Object Name>;

 

Example: Student S1;

 

Before we start using the object, we need to instantiate it. Instantiation involves memory allocation and other basic initializations contained in the objectâs constructor. We use the new keyword to instantiate objects. The syntax for which is given below:-

 

Note: Constructor is a special member function of a class that is used to initialize the data members. It will be dealt with, in later tutorials.

 

<Object Name> = new <Class Name>;

 

Example Usage: S1 = new Student();

 

These two steps can be done in a single line of code as Student S1 = new Student();

 

Using the Objects

We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student classâs S1 object we write S1.Display();

 

Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;

 

Releasing Memory

To release the memory occupied by the object we use S1 = null;

 

Example Program:-

 

using System;namespace CSTutorials{	class Student	{		// Data Members		public string Name;		public int Age;		// Member Function		public void Display()		{			Console.WriteLine("Name {0}\n Age {1}", Name, Age);		}	}	class Program	{		static void Main(string[] args)		{			Student S1;			 // Declaration			S1 = new Student();	 // Instantiation			Student S2 = new Student();	 // Single line Declaration & Instantiation			// Assigning value to member variables			S1.Name = "Michael";				S1.Age = 37;						S1.Name = "Kimi";			S2.Age = 25;			// Invoking member function			S1.Display();		   			S2.Display();		   			Console.ReadLine();		}	}}
Benefits of Object Oriented Programming

Realistic Modeling: Living in a âWorld of Objectsâ, the model built on real life is a much better approach because it allows issues to be tackled with greater accuracy.

Re-usability of code: Think of a scenario where a car making company specialized in two seaters decides to launch a four seater model. Converting the two seater model to a four seater is easier than designing a new model altogether.

Resilience to change: Being compartmentalized, individual objects can be improved without having to re-package the entire software.

Polymorphism: The behavior of an object can depend upon the state its in, thus exhibiting Polymorphism. Consider a car colliding with a wall. The impact of the process would depend upon the approach speed of the car, the Angle it strikes in, the strength of the wall and so on. If two cars were to collide, the results would be much different, with both of them receiving considerable damage.

Previous Tutorial - Lesson 3 - Programming Constructs

 

Next Tutorial - Lesson 5 - Encapsulation & Abstraction

 

Lesson: 1 2 3 4 5 6 7

Edited by turbopowerdmaxsteel (see edit history)

Share this post


Link to post
Share on other sites

Access Specifier in C#

C# Tutorial : Lesson 4 - Object Oriented Programming

 

What are the access specifier in c#?

 

What was the main difference between Internal and protected access specifier?with example...

 

I need a brief explanation for Internal and protected access specifier?

 

-question by santhanalakshmi

Share this post


Link to post
Share on other sites

There are four access specifiers in C#:

public

internal

protected

private

The above list is in the order of decreasing visibility. Members declared as public can be accessed from anywhere. The internal access specifier can be thought of as application public, i.e a member declared internal can be accessed from any other class belonging to the assembly. A protected member is public across the class hierarchy but private outside it. Protected members can be accessed in the child (derived classes). Those declared private can only be accessed inside the same class.

 

public class Base{	protected int Var1;	internal int Var2;}public class Derived : Base{	public void MyMethod()	{		// Bot Members are inherited		Var1 = "Value";		Var2 = "Value";	}}public class Unrelated{	public void MyMethod()	{		Base B = new Base();		B.Var1 = "Value";	// Compile Error (Var1 cannot be accessed from this class)		B.Var2 = "Value";	}}

The above code contains three classes: Base which declares two variables and is the base class for class Derived. A third class Unrelated exists in the same assembly. As you can see, Var1 and Var2 get inherited to the Derived class. As such, they are directly usable by a method of the class. Class Unrelated is not derived from class Base. It can however, access the members of class base by creating an object of it. internal members being public for the assembly are accessible through the Unrelated class. But, the protected variable Var1 is not accessible because Unrelated is not derived from class Base or any of its child classes.

Share this post


Link to post
Share on other sites
public data membersC# Tutorial : Lesson 4 - Object Oriented Programming

hey , I wondered about the declaration of public data members in the c# class.

why it is supposed for me to write public keyword before every data member that I want to be public ??! 

class student{   public string name;

  public string address;   public int grade;   public int age;

}

why not I write just one public keyword in the begin and all below data members become public such as in C++ ...!! 

Is there are any way to do that in c# I.E declaring many public data members with only one public keyword????

thanks alot

-question by smsma

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.