C# : Creating a Custom Class

Overview

If you are familiar with creating classes in C/C++, I have some good news and some bad news...

Good news: The concept of classes is the same in every OOP language, so you're at least one step ahead of new programmers.

Bad news: The syntax you used in C/C++ is different enough that you're probably going to spend a lot of time cursing at the C# compiler...

Similiarities

Like I mentioned before, C# uses the same OOP model that you learned in C/C++. You still specify the various accessibility levels of your object's attributes and actions. You must still provide constructors for your class objects. Also, inheritence and polymorphism are implemented in much the same way as in C/C++.

Differences

The most glaring difference between a C# class and a C/C++ class is, obviously, the syntax. While the basic OOP concepts are the same in C# as in C/C++, the code to implement a class is quite different.

Take a gander at this sample I put together for you:

• SampleClass.cs

class SampleClass
{
   public SampleClass( void ) // constructor
   {
   /* place code here that needs to execute
   when an instance of our class is created */
   }

   public ~SampleClass( void ) // destructor
   {
   }

   // private internal variables and functions go here
   private Int32 mySampleValue;

   /* public shared variables and external functions
   go here */
   public Int32 GetSample()
   {
       return mySampleValue;
   }

   public void SetSample( Int32 value )
   {
       mySampleValue = value;
   }

}

The low-down...

In C#, classes are implicitly public. While I believe the C# compiler will allow you to make a class private, it ultimately is an excercise in futality to do so, as you will never be able to create an instance of your class if it is private.

One thing I don't miss about C/C++ when I code in C#: there are no header files. C# classes are self-contained. Also, methods/functions in C# must be contained within a class, so no more global functions. C# does implement static functions, so it is possible to have a shared method/function.

Back to top Comments ( 0 ) • Login to comment.

Sorry. There are currently no comments for this article.