[
Advertise | Submit Code | About us | Contact us | Link us
]
Go!
Membership Services
Login
Register

Home
C# General

General

C# Language

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting
C# Windows Forms

General

Combo and List boxes

Miscellaneous Controls

Button Controls

Edit Controls
Cutting Edge

ASP.NET 2.0

Visual Studio 2005

Windows Longhorn

SQL Server 2005
C# Multimedia and GDI+

General

DirectX

GDI+

Audio
Internet & Web

General

Images and multimedia

Database

Utilities

Security

ASP.NET Controls

Design and Architecture

Webservices
.NET

General

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting

ADO.NET

XML.NET

Tools

Enterprise

IDE
Visual Basic .NET

VB.NET General

VB.NET Controls
General Reading

.NET Books Review

Product Showcase

Book Chapters

Business Design & Strategy
Community

Discuss

Job Board

Discussion

CodeXchange
DeveloperLand

Advertise

Submit Code

About us

Contact us

Link us
Miscellaneous

Favorite Links

Downloads

Programming Sites

Top Stories
Regular Expressions

E-Mail

Date/Time
Home > C# General > C# Language
Objects and Classes in C#, Part II
Posted by on Monday, September 20, 2004 (EST)

In this article I explained the concepts behinds Objects and Classes but I didn't discuss why Object Oriented Programming (OOP) uses the Object and Class technique

This article has been viewed: 3,065 times
Technology: C# Language.

Contents

Introduction

After I wrote the article named Introduction to Objects and Classes in C#, I got a lot of e-mail messages asking me to create a series of articles about Objects and Classes. Actually this was a few months back (sorry for being late), but I'm here again with part two. In Part one, I explained the concepts behinds Objects and Classes but I didn't discuss why Object Oriented Programming (OOP) uses the Object and Class technique. Today, I will discuss the advantage of Objects and Classes with more details on how to understand your problems and develop your Objects for your solution.

Because this series targets the true beginners, I will not use any technical expressions and I will prefer to explain concepts by examples. I presume that readers have a basic knowledge of C# (control the flow of the program, using methods and arrays, namespaces & assemblies).

The first thing that you should know about C# programming is that it uses the Class to include the data (in part one, I said that data can be stored in instance variables in the class) and methods to process that data. Think about it in the next example:

class Test
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

The class Test contains a method called Add (which add to integers and return the result) is a good example for what we are talking about. I said that the Class includes data and there are methods to process that data, here the class test includes the method Add() which takes two integer numbers to add them and this is the functionality of the method. The application that will use the Test class can be something like the following:

public class Class1
{
    public Class1()
    {
        Test t1 = new Test();
        Console.WriteLine(t1.Add(5,4));
    }
}

The concept of Objects & Classes helps you hide your code implementation from the user of your class. In other words, if you develop a class for your friend to use, he doesn't have to know how you created the methods of that class in order to use it; he'll just need to know how to use it, and what functionality is offered by your class members. The point here is that you don't have to know how another developer developed a certain class; you just have to know how to interface with it. And I said in the first part, when you develop programs with C# you will develop classes. Note that this is not like C programming, where the programming primary building block was the function (or methods, in C#). Finally, remember that C# defines other types like structures, enumerations. We'll learn about these in future articles.

In C programming language, programmers develop functions to form their applications. These functions contain the code of the program. The problem is that in large programs, if you have to modify just one line of code you may have to modify many functions to fit in the new modifications. (In procedural languages, functions depend on each other.) But in C#, we write classes as our primary building blocks, and because classes hide their code implementation -- and only the methods of these classes are accessible to the applications that use them -- if we must change something inside the class, we will do it without changing the code of the applications that uses our classes.

When you write applications in C# try to use comments to describe exactly how your application performs and why; try to make your application easy to understand and easy to maintain. Think about it this way: if you were to come back to your application five years after you wrote it, would you know what every line of code meant and did? What if someone was developing an application and they were trying to read through your code? Without documentation, this is difficult even for the most experienced programmers.

I think that you want to know more about classes so let's write a class and then discuss  new concepts.

The Person Class

Here's a simple class called Person

class Person
{ 
    // These are 3 private instance variables
    // for now just consider them instance members of 
    // that class
    private string firstName;
    private string lastName;
    private int age; 
    // This called the default constructor
    public Person()
    { 
        firstName = "Unknown";
        lastName = "Unknown";
        age = 0; 
    } 
     
    // This also a Constructor and we will understand
    // the use of it and why we create constructors
    public Person(string fName, string lName, int pAge)
    {
        firstName = fName;
        lastName = lName;
        age = pAge;
    } 
 // This is a method just writes a string to the console.
 // this string consists of the 3 variables and
 // displaying the information about the person. 
 public void PersonInfo()
 { 
  Console.WriteLine("First Name = {0}, Last Name = {1} and his age = {2}",
  firstName, lastName, age); 
 }
}

Let's break this down:

You're probably curious about private string firstName, private string lastName, and private int age. These are called instance variables, and as you know from the first part of that article, when you create objects from a given class (for example, the person class) you create an instance of that class. That's why we call the variables declared the body of the class (but not inside any method of that class) an instance variable. When you create an objects of that class C# compiler will allocate separate memory locations for the instance variables of each object. Thus, the object named Michael (of type Person) will contain its own values for these instance members, as will the object Prakhar (of type Person). You can say that the consumer application (the application that will use your class) will provide the values of these instance variables for each object created of that type.

NOTE About the keywords private and public in the class, they called access modifier keywords. When developing C# class you will use the access modifier keywords to specify the scope of the member. Each instance variable, method, or any other type you create inside a class called a member. C# gives you the power to specify the scope of the member using these access modifiers.

Simply, the scope of a type (a variable, a method, or a class) is where you can use that type in your program. In other words, the scope defines the area of the program where that type can be accessible and referenced.

When you declare a variable inside a block of code (like a method or an if statement structure), it will have a local scope, and it will be called a local-variable. Local scope means that you can't refer to that variable outside that block of code. Consider the next example.

class Test
{ 
    public void Test1()
    {
        int x = 0;
            // some code goes here that uses the x variable
    } 
     
    public void Test2()
    {
        Console.WriteLine(x);
    } 
}

Try to instantiate this class and you will get a compile-time error inside method Test2() telling you that the name x doesn't exist and that's because x is a local variable to the method Test1() and method Test2() doesn't know anything about it. So x has a local score to method Test1() only. Consider the next example.

class Test 
{ 
    public void Test1()
    {
        int x = 0; 
        if(x == 0)
        { 
            Console.WriteLine("x equal to 0");
        }
    }
}

Here, the method Test1() declares a local variable x (now x has a local-scope to the method). Try to instance this class and compile the code. It will work! Some beginners think that because I said that x has a local scope to method Test1() it will not be referenced from nested block (like the one we have here, the If statement) but that's not true because any nested block inside Test1() method can refer x because x is local for the method and its all blocks of code.

NOTEThere are 2 kinds of scopes: block scope (the one that we just finished), and a class scope (which we will talk about later in this article). Now, about the keywords private and public in the class person, you can use these access modifier keywords to define the scope of your variables, methods, or even your classes. There are other access modifiers but I will talk about them in a later article when I will explain the concepts of inheritance.

Instance variables declared using the access modifier keyword private will be accessible to the methods between the opening left brace "{" and the closing right brace "}" (which define the body of the class) only. In other words, when you declare an instance variable like in the following example:

public class Class2
{
    private int x;
} 
public class Class3
{
    void testing()
    {
        x == 100;
    }
}

In this example, you will get a compile-time error telling you that you that the name X doesn't exist inside the Class3. Using the keyword private, you explicitly tell the compiler "Don't show this member to any other class." (So you are hiding it inside the class.)

What about objects of that class? Can they access the members declared as private?

In short, no, the objects of this class will not see the private member, but it will have it's own copy because as we said before the class is just a template for the contents of its object. I prefer to discuss it using an example:

public class Class2
{
    private int x = 100;
}

And then I will instance 2 objects of that class inside the Main method

static void Main(string[] args)
{
    Class2 c2 = new Class2();
    Class2 c3 = new Class2();
    // Now Let's check if we can see
    // x inside any of these objects
    c2.
}

c2 and c3 are objects of type Class2() but look what happened when I typed the "." operator (which will get us all the accessible members of that class).

There is no x here because it's private to the class. You may wonder why this feature exists. Sometimes you need to hide some values inside the class (ie. you don't want other classes or objects of that class to see these values), maybe because it's complex information, or it's private to your work, or the developers that will use your class (after it's compiled) will simply not benefit if they saw these variables or methods.

You can use the access modifier keyword public while you declare your variables to specify that you want your variable to be accessed by the other classes or any objects of this class. let's revise the the x variable in Class2 and check if we can see it or not (from objects of this class or other classes).

Oh, yes we can see the x variable now because we made it public. And I will talk about Class Scope in a later article. For now, just play around with scopes. I think you'll have a lot of fun with these.

Top Go to Table of Contents

About michael labib

Click here if you want to know more about .

Other articles that may interest you

  • Write a Word Add-In – Part 0
  • Write a Word Add-In – Part I
  • Lengthy Operations on Single Thread in .NET Application
  • Learning Draughts
  • Exceptions and Performance
  • Average Rating :

    Discussion Forums
    Got a programming related question? Hopefully someone has the answer... Want to help out other developers? Visit our discussion forums.

    Sponsored by:

    New Articles

  • Exceptions and Performance
    Almost every time exceptions are mentioned in mailing lists and newsgroups, people say they're really expensive.Let's examine that claim, shall we?

  • Creating multilingual websites - Part 1
    Extend the existing globalization capabilities of .NET to create flexible and powerful multilingual web sites. First, create a custom ResourceManager, and then create custom localized-capable server controls to easily deploy multilingual functionality.

  • Parameter passing in C#
    Many people have become fairly confused about how parameters are passed in C#, particularly with regard to reference types. This page should help to clear up some of that confusion

  • Most Popular Articles

  • LDAP, IIS and WinNT Directory Services
    This article explains how to use .NET Directory Services to retrieve and search directory objects, create new directory objects and edit or delete existing directory objects. Describes Active Directory Application Mode (ADAM) and how to use the IIS, WinNT and LDAP directory (ADSI) provider.

  • An in-depth look at WMI and instrumentation, Part II
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article is the second part of a two-part series.

  • An in-depth look at WMI and instrumentation, Part I
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article provides an in-depth look at WMI and MOM 2005

  • New Books

  • Murach's ASP.NET 2.0 Upgrader's Guide: VB Edition
    What’s new and how to use it! That’s what this book delivers if you’re a VB developer who’s interested in upgrading from ASP.NET 1.x to ASP.NET 2.0.

  • C# in easy steps
    Learn to program with Microsoft’s premier programming language. No previous programming knowledge is assumed. With numerous easy-to-follow examples, this title explains the essentials of object-oriented programming with C#.

  • Murach's ASP.NET web programming with VB.NET
    Murach's ASP.NET web programming with VB.NET by Doug Lowe and Anne Prince is a in depth training and reference book for ASP.NET programming using VB.NET. The book builds upon Murach's previous books and covers more advanced concepts for programming ASP.NET pages.

  • Got Code?

    if you have any article , source code , or anything else you'd like to share with this community that you think others might find useful, please submit it here and we will gladly make it available on this site. submit@developerland.com.
    Partners

    All articles are copyrighted by their individual authors unless otherwise specified , everything else Copyright ©2004-2006 DeveloperLand