CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> .NET / C# >> C# >> Basic Syntax >> Anand C# Tutorials


Understanding Classes, Methods, and Properties in C#
Rating:

Anand Narayanaswamy (view profile)
September 27, 2002

By Anand Narayanaswamy

A class is the fundamental topic to be discussed in any Object-Oriented Programming (OOP) language. This also is true with C#. Basically, we have to discuss the meaning of class with reference to an object also. This is because these two words are more or less interrelated. A class is a combination of related objects whereas each object is an instance or a copy of the corresponding class.


(continued)



From the figure given below (see Figure 1), we can judge the fact that Telephone is a combination of Sony, Ericcson, Panasonic, and Siemens. Hence, Telephone is a class and the other four are its objects. Here, Compaq and HP can't be objects of the class Telephone. In C#, a class is a user-defined reference type. We create an object out of the classes by using the "new" keyword and by applying the general syntax as shown in Listing 1:

Listing 1

Classname objectname = new Constructor();

We will discuss constructors later. Therefore, to create an object for our class Telephone, you have to code as shown in Listing 2:

Listing 2

Telephone T= new Telephone();



Click here for a larger image.

Figure 1 - Structure of a Class

To access any variable by using the above object name, we use the dot operator as shown in Listing 3:

Listing 3

using System;
class Access
{
  //Variables declared outside the main.
  int x = 100;
  int y = 200;

  public static void Main()
  {
    //Object created
    Access a = new Access();

    //Instance variables called
    Console.WriteLine(a.x);
    Console.WriteLine(a.y);
  }
}

In Listing 3, the variables are declared outside the main method. Hence, they are called Instance Variables. You have to create an object only for accessing an Instance variable. The additional memory created out of the object creation are automatically destroyed by the C# Garbage Collector.

Methods

In this session, we will deal with Methods. The various types of methods will be discussed in detail.

Methods are blocks of code that perform some kind of action, or carry out functions such as printing, opening a dialog box, and so forth. There are two kinds of methods in C#, as there are in Java. They are:

  • Instance Method
  • Static Method

Let's discuss each of these in detail. Instance Methods are methods declared outside the main method and can be accessed only by creating an object of the corresponding class, as shown in Listing 4:

Listing 4

using System;
class Instmethod
{
  //Method declared outside the main.
  void show()
  {
    int x = 100;
    int y = 200;
    Console.WriteLine(x);
    Console.WriteLine(y);
  }

  public static void Main()
  {
    //Object created
    Instmethod a = new Instmethod ();

    //Instance method called
    a.show();
  }
}

Class methods also are declared outside the main method but can be accessed without creating an object of the class. They should be declared with the keyword static and can be accessed using the classname.methodname syntax. This is illustrated in Listing 5. Similarly, you also can create class variables.

Listing 5

using System;
class Statmethod
{
  //A class method declared
  static void show()
  {
    int x = 100;
    int y = 200;
    Console.WriteLine(x);
    Console.WriteLine(y);
  }

  public static void Main()
  {
    // Class method called without creating an object of the class
    Statmethod.show();
  }
}

Declaring Methods with Parameters

You can declare methods with a variable name or names as a parameter, as shown in Listing 6:

Listing 6

void display(int x) { }

At the time you access the method, you should pass a value to the same, as in the code snippet shown in Listing 7:

Listing 7

//object S created
S.display(50);

The complete code to illustrate the above concept is shown in Listing 8:

Listing 8

using System;
class Pmethod
{
  //Method declared with two parameters x and y of type integer
  void show(int x , int y)
  {
    Console.WriteLine(x);
    Console.WriteLine(y);
  }

  public static void Main()
  {
    //Object created
    Pmethod a = new Pmethod ();

    //Method called by passing two integer values
    a.show(200,250);
  }
}

Method Overloading

In the preceding example, we declared a single method with a single parameter. But you can declare the signature of the same method once again in the same class but with different parameters. The parameters should be different. If not, the C# compiler would show errors. Listing 9 clearly explains this concept.

Listing 9

using System;
class Overloadmethod
{

  //Method declared with one integer parameter
  void show(int x)
  {
    Console.WriteLine(x);
  }

  //Method declared with two integer parameters
  void show(int a, int b)
  {
    Console.WriteLine(a);
    Console.WriteLine(b);
  }

  public static void Main()
  {
    //Object created
    Overloadmethod a = new Overloadmethod ();

    //Methods called by passing respective values
    a.show(100);
    a.show(300,500);
  }
}

Properties

Properties provide added functionality to the .NET Framework. Normally, we use accessor methods to modify and retrieve values in C++ and Visual Basic. If you have programmed using Visual Basic's ActiveX technology, this concept is not new to you. Visual Basic extensively uses accessor methods such as getXXX() and setXXX() to create user-defined properties.

A C# property consists of:

  • Field declaration
  • Accessor Methods (getter and setter methods)

Getter methods are used to retrieve the field's value and setter methods are used to modify the field's value. C# uses a special Value keyword to achieve this. Listing 10 declares a single field named zipcode and shows how to apply the field in a property.

Listing 10

using System;
class Propertiesexample
{

  //Field "idValue" declared
  public string idValue;

  //Property declared
  public string IdValue
  {

    get
    {
      return idValue;
    }
    set
    {
      idValue = value;
    }
  }

  public static void Main(string[] args)
  {

    Propertiesexample pe = new Propertiesexample();
    pe.IdValue = "009878";
    string p = pe.IdValue;
    Console.WriteLine("The Value is {0}",p);
  }
}

If you look at the MSIL generated by the code in Listing 10, you can view two methods, as shown in Listing 11:

Listing 11

Address::get_Zip() and Address::set_Zip().

We have reproduced the code for your reference. On careful scrutiny, you can see that the set_zip() method takes a string argument. This is because we have passed a string value while accessing the property. It's illegal to call these methods directly in a C# program.

In the preceding code, the Address.zipcode property is considered a read and write property because both getter and setter methods are defined. If you want to make the property read-only, omit the set block and to make it write only, omit the get block.

About the Author

Anand Narayanaswamy works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials. He can be reached at anand@learnxpress.com.

About the Author

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
No Comments Posted.
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES