Recent

  • C# Tutorial - Aggregation and Composition When do you make an object inherit from another object and when do you make an object become part of another object? So far we have looked at inheritance, but ...
    Posted Jun 28, 2011, 7:35 PM by magic stone
  • C# Tutorial - Polymorphism Polymorphism comes from the Greek words of poly and morphos. The literal translation means "many forms", which in essence is how we use polymorphism in programming.The easiest way to ...
    Posted Jun 28, 2011, 7:31 PM by magic stone
  • C# Tutorial - Reasons for Inheritance Inheritance can be implemented in a variety of ways for a variety of reasons. Listed below are some of those reasons.Inheritance for SpecializationThe most common use of inheritance ...
    Posted Jun 28, 2011, 7:29 PM by magic stone
  • C# Tutorial - Inheritance Inheritance represents the relationship between two objects A and B, such that B 'is a kind of' A. In UML, we show this by using the triangle symbol. We can ...
    Posted Jun 28, 2011, 7:27 PM by magic stone
  • C# Tutorial - Access Modifiers and Properties Each part of an application, whether it is a class, structure, enumeration or other object can be set so that another part of the application can either see it or ...
    Posted Jun 28, 2011, 7:16 PM by magic stone
  • C# Tutorial - Encapsulation and Data Hiding EncapsulationThe idea of encapsulation comes from the need to cleanly distinguish between the specification and the implementation of an operation and the need for modularity. Modularity is necessary to ...
    Posted Jun 28, 2011, 7:13 PM by magic stone
  • C# Tutorial - Scope When using variable within a control structure, the variable only has scope with the curly brackets that it is declared between. Once the structure has finished, the variable goes out ...
    Posted Jun 28, 2011, 7:12 PM by magic stone
Showing posts 1 - 7 of 18. View more »

C# Tutorial - Aggregation and Composition

posted Jun 28, 2011, 7:33 PM by magic stone   [ updated Jun 28, 2011, 7:35 PM ]

When do you make an object inherit from another object and when do you make an object become part of another object? So far we have looked at inheritance, but object oriented programming also includes another method for relationships between classes, that is when one object forms part of another object.

Aggregation and composition are very similar in nature. These relationships form a whole-part relationship that you can use to decompose objects into more manageable entities. The difference between aggregation and composition is that any object that can exist and be used independently uses aggregation, and an object that has no meaning outside of the relationship uses composition.

For example, a class named Car would have an engine. More importantly, we can recognize objects that fall into this relationship by the use of the term "is a part of", whereas inheritance uses the term "is a kind of". So back to our example, "an engine is a part of a car".

In UML, an object relationship that is formed by aggregation is drawn using an empty diamond. An object relationship that is formed using composition is drawn using a filled diamond.

The following UML diagram illustrates the concepts of aggregation and composition.


In the diagram above, the battery and the engine have no meaning outside of the car, as the car cannot work without either of them, so the relationship is formed using composition. However, a car can work without doors, so the relationship is formed using aggregation.

Coding Aggregation and Composition

From the previous diagram, we can create a possible small code sample that shows the two forms of relationship.

namespace MyCars
{
  public class Car
  {
    // Aggregation uses instances of objects created outside of
    // this class
    protected Door _frontRight;
    protected Door _frontLeft;
    protected Door _rearRight;
    protected Door _rearLeft;

    // inner classes used to create objects that are intrinsically
    // linked to the class Car
    protected class Engine
    {
      public int _horsePower;
    }

    protected class Battery
    {
      public int _voltage;
    }

    // Composition uses instances of objects that are created as
    // part of this object
    protected Engine _theEngine;
    protected Battery _theBattery;
  }

  public class Door
  {
    public int _position;
  }
}

By giving each of the members protected access modifiers, each class that inherits from Car has access to each of the members of the class Car.

namespace MyCars
{
  // Inherit from class Car
  public class FordCapri : Car
  {
    public FordCapri()
    {
      _theEngine._horsePower = 2000;
    }
  }
}

C# Tutorial - Polymorphism

posted Jun 28, 2011, 7:31 PM by magic stone

Polymorphism comes from the Greek words of poly and morphos. The literal translation means "many forms", which in essence is how we use polymorphism in programming.

The easiest way to think about polymorphism is to use an example. Suppose that we are creating a piece of software such as a drawing/image package. As we draw shapes, we want to keep a list of what we add, this way we can remove them using the undo function. So if we created a collection of shapes, we could put squares, pentagons, or any of the shapes into the collection and the behaviour that they respond to is the same for each object in the collection.

A shape has many forms. Shape is just the generic name for them.

Coding Polymorphism

To demonstrate this lets look at some simple shapes. The base class will obviously be named Shape:

abstract class Shape
{
  public Point _loc;
  public Size _sz;

  public virtual void Draw(Graphics g)
  {
  }
}

The abstract keyword enables you to create classes solely for the purpose of inheritance. An abstract class can not be used to create an object.

The virtual keyword is used to modify a method declaration, and allow it to be overridden in a derived class.

Now let's create a derived class named Square:

class Square : Shape
{
  public override void Draw(Graphics g)
  {
    Pen p = new Pen(Color.Black, 3);
    g.DrawRectangle(p, _loc.X, _loc.Y, _sz.Width, _sz.Height);
    p.Dispose();
  }
}

We override the Draw method in order to draw our square on the screen.

Similarly let's create a class named Pentagon:

class Pentagon : Shape
{
  public override void Draw(Graphics g)
  {
    Pen p = new Pen(Color.Black, 3);
    Point[] pts = new Point[6];
    float a = 0;
    for (int c = 0; c < 5; c++)
    {
      pts[c] = new Point(
        (int)(_loc.X + ((_sz.Width / 2) * Math.Cos(a)) 
           + _sz.Width/2),
        (int)(_loc.Y + ((_sz.Height / 2) * Math.Sin(a))) 
           + _sz.Height/2);
      a += (float)Math.PI * 2 / 5;
    }
    pts[5] = pts[0];

    g.DrawPolygon(p, pts);
    p.Dispose();
  }
}

So now we have our shapes, we could have a collection class to hold our shapes called ShapeCollection.

class ShapeCollection : CollectionBase
{
  public void Add(Shape s)
  {
    List.Add(s);
  }
}

So we give ourselves an instance on the class and add our shapes to it.

ShapeCollection Shapes = new ShapeCollection();

for (int i = 0; i < 10; i++)
{
  Shape s = null;

  if ((i % 2) == 0)
    s = new Square();
  else
    s = new Pentagon();

  s._loc = new Point(20 + (i * 20), 20 + (i * 20));
  s._sz = new Size(20, 20);
  Shapes.Add(s);
}

We can now get each shape to draw itself

foreach (Shape s in Shapes)
  s.Draw(e.Graphics);

C# Tutorial - Reasons for Inheritance

posted Jun 28, 2011, 7:29 PM by magic stone

Inheritance can be implemented in a variety of ways for a variety of reasons. Listed below are some of those reasons.

Inheritance for Specialization

The most common use of inheritance is to subclass for specialization, this way a special version of the parent class is created that still satisfies the specification for the parent class. The child class subtype is substitutable for the parent class and so the principles of substitutability are upheld.

Inheritance for Specification

A frequent use of inheritance is to ensure that classes maintain a common interface. Each of the child classes has the same interface that implements the methods declared in the parent class. Often the parent class is an abstract class that cannot be created as an object itself.

Inheritance for Extension

The child class keeps the functionality of the parent class intact without changing or overwriting any of it. It then adds its own functionality to extend that of the parent class, changing the interface overall.

Inheritance for Construction

This use of inheritance is where the child class requires all of the desired functionality offered by the parent class, but there is no abstract relationship between the child and the parent class. The child class is not a form of the parent class.

Inheritance for Generalization

A form of inheritance generalizes the functionality found in the parent class by overriding the methods in the child class.

Inheritance for Limitation

Sometimes there is a need to limit the interface of the parent class within the child class. This is not a very desirable method of inheritance, but can be managed by limiting the parent class in the first place and creating a second child class with the additional functionality that was in the original parent class.

Inheritance for Combination

This is similar to construction, but the child class requires elements from two classes. Multiple-inheritance is not possible through C#, however a child class can inherit from a parent class whilst implementing an interface also.

Interfaces

An interface looks like a class, but has no implementation. They can contain methods, properties, events, and indexers (a member that enables an object to be indexed similar to an array).

Following from the previous inheritance example, we can create an interface:

interface IIntelligence
{
  // Method
  bool behaviour();

  // Property
  int IQ
  {
    get;
    set;
  }
}

Interfaces are implemented in the same manner as inheritance through the colon (:). When implementing interfaces, a comma (,) is used to separate the interfaces/or classes that are being derived from.

So the Terrier class can implement the IIntelligence interface.

public class Terrier : Dog, IIntelligence
{
  public Terrier()
    : base()
  {
  }

  private string species = "Terrier";
  public override string getSpecies() { return species; }

  private int _iq;
  public int IQ
  {
    get { return _iq; }
    set { _iq = value; }
  }

  public bool behaviour()
  {
    return true;
  }
}

The Terrier class now inherits from the Dog class and implements the IIntelligence interface. Thus Inheritance for Combination is demonstrated.

C# Tutorial - Inheritance

posted Jun 28, 2011, 7:25 PM by magic stone

Inheritance represents the relationship between two objects A and B, such that B 'is a kind of' A. In UML, we show this by using the triangle symbol. We can use the objects that we have already been looking at to expand on this concept. We have a 'person' object and a 'dog' object, so how are they related? A 'dog' is an animal, more specifically a 'dog' is a mammal. A 'person' is also a mammal, so we have found a common parent for the two objects. As we have seen in previous pages, the 'person' and 'dog' objects share an amount of common information and subsequently common behaviour. It is this common data that they both get from the parent object, so we could create an object that has the common data within it.


In the previous diagram, I have tried to show one possible hierarchical structure that will allow the 'person' object and the 'dog' object to share common data logically. However, the diagram shows a flaw in our thinking, 'dogs' can be domestic or wild. A 'wild' dog will not have a name or address, so we need to clarify each type of 'dog' object with a unique identity. So we may have our 'dog' object representing domestic dogs, while we change the object name to 'WildDog' for the other object of type 'dog'.

Finally I have shown that we can inherit from our dog objects into individual breeds of dog if we wished to.

In general when talking about inheritance, we talk about a type of object. An object inherits from a parent, known as its super-type. A child is inherited from an object and is known as a sub-type.

Coding Inheritance

You create a derived class by adding a colon after the name of the derived class, followed by the name of the base class:

public class Terrier : Dog

This code declares a new class, Terrier derived from Dog. You can read the colon as "derives from." The derived class inherits all the members of the base class, both member variables and methods. The derived class is free to implement its own version of a base class method or variable. It does so by marking it with the keyword new. This indicates that the derived class has intentionally hidden and replaced the base class member.

class Dog
{
  private string species = "Dog";
  public virtual string getSpecies() { return species; }
}

class Terrier : Dog
{
  new private string species = "Terrier";
  public override string getSpecies() { return species; }
}

The species variable above overrides the base class variable of the same name.

Dog myDog = new Dog();
Terrier myTerrier = new Terrier();

Console.WriteLine("The species of myDog is {0}", myDog.getSpecies());
Console.WriteLine("The species of myTerrier is {0}", myTerrier.getSpecies());

// Output
The species of myDog is Dog
The species of myTerrier is Terrier

Calling Base Class Constructors

The Terrier constructor would invoke the constructor of its parent by placing a colon (:) after the parameter list and then invoking the base class with the keyword base. If the base class has an accessible default constructor, the derived constructor is not required to invoke the base constructor, as the default constructor is called implicitly. If the base class does not have a default constructor, every derived constructor must explicitly invoke one of the base class constructors using the base keyword.

public Terrier() : base()

Calling Base Class Methods

If a class needs to call a method in the base class then this is achieved using the base keyword followed by the method required in the usual manner using dot notation.

base.getSpecies();

C# Tutorial - Access Modifiers and Properties

posted Jun 28, 2011, 7:15 PM by magic stone

Each part of an application, whether it is a class, structure, enumeration or other object can be set so that another part of the application can either see it or not. This is what makes encapsulation and data-hiding work, as we have previously seen and is achieved through the use of access modifiers. The most commonly used modifiers are privateprotected and public.

An attribute or method marked private can only be seen from within the class that it is defined within. When using data-hiding, all attributes are marked private. If you mark something private outside of a class or struct, a compile time error will occur.

An attribute or method marked public can be accessed from any class that has access to the class members. There is no restriction on accessing public members. When using data-hiding, the methods used to access the private attributes will be declared public.

An attribute or method marked protected can only be seen from within the class that it is defined within or from within a class that inherits from the class that it is defined within. This is useful when allowing derived classes access to the attributes of the base class.

C# defines a fourth access modifier, internal, which allows members to be accessible from within the same assembly of which it is defined. This is a good method of allowing several classes to share some common data.

Finally a fifth access modifier, protected internal, this can be seen as protected OR internal, and not protected ANDinternal for which there is no concept.

In general, attributes of a class are designated as private and the methods that act upon the attributes are designated aspublic.

  • If you do not give a class an access modifier, it will default to public, because a class cannot be private unless it is an inner class.

  • If you do not give a method an access modifier, it is defaulted as private.

  • If you do not give an attribute an access modifier, it is defaulted as private.

Access ModifierRestrictions
publicNo restrictions. Attributes and methods marked public are visible to any method of any class.
privateThe Attributes and methods in class A which are marked private are accessible only to methods of class A.
protectedThe Attributes and methods in class A which are marked protected are accessible to methods of class A and also to methods of classes derived from class A.
internalThe Attributes and methods in class A which are marked internal are accessible to methods of any class in A's assembly.
protected internalThe members in class A which are marked protected internal are accessible to methods of class A, to methods of classes derived from class A, and also to any class in A's assembly.

Properties

Properties allow users to access class variables as if they were accessing member fields directly, while actually implementing that access through a class method.

The user wants direct access to the variables of the object and does not want to work with methods. The class designer, however, wants to hide the internal variables of his class in class members, and provide indirect access through a method. By decoupling the class variables from the methods that access those variables, the designer is free to change the internal state of the object as needed.

Coding Properties

The code below shows how to create a private variable with its associated properties.

// private member variables
private int hour;

// create a property
public int Hour
{
  get { return hour; }
  set { hour = value; }
}

We would access the properties in the following manner:

// Get the current value of hour to local variable iHour
int iHour = aClass.Hour;

// Increment iHour
iHour++;

// Write iHour back to hour
aClass.Hour = iHour;

C# Tutorial - Encapsulation and Data Hiding

posted Jun 28, 2011, 7:13 PM by magic stone

Encapsulation

The idea of encapsulation comes from the need to cleanly distinguish between the specification and the implementation of an operation and the need for modularity. Modularity is necessary to structure complex applications designed and implemented by a team of programmers.

Encapsulation is a way of binding information and the behaviour performed upon the information together in a single object. This allows the user of the object, to see and use the interface of the object without needing to know the internal workings of the object.

The idea of encapsulation in programming languages comes from abstract data types. In this view, an object has an interface part and an implementation part. The interface part is the specification of the set of operations that can be performed on the object and is the only visible part of the object.

In encapsulation, there is a single model for data (information) and operations (behaviour), and information can be hidden. No operations, outside those specified in the interface, can be performed.

Encapsulation provides a form of "logical data independence": we can change the implementation of an object without changing any of the programs using the object. Encapsulation is obtained when only the operations are visible and the data and the implementation of the operations are hidden within the object.

An Example

In our everyday lives, most of us use a video recorder via either the controls on the front of it or via a remote control. We all know which buttons to press in order to watch a program or record a program, this is done via the interface we have with the video recorder. The manufacturer can change the internal workings of the hardware, but this would not often affect us as a user because the interface we have would be the same. That is a play button, a record button, fast forward, rewind, stop, pause, etc.

The VCR is encapsulated as a single object, which may change internally, but stays the same from the users interface point of view.

Coding Encapsulation

The following code demonstrates a class containing some data and a method that acts upon the data (without data hiding):

class Counter
{
  public int Count;

  public Counter()
  {
    Count = 0;
  }

  public void incCount()
  {
    Count++;
  }
}

Although the member variable can be directly accessed, the data and its method is encapsulated in a class.

Data Hiding

Data hiding is linked to encapsulation; however data hiding is not encapsulation as it is sometimes described in this way.

Data hiding is simply the means to remove direct access to an object’s information, by providing operations that perform actions on the data. This way any changes to the value of the data must come through the interface to the data, which is an operation. Thus we use access operations or properties.

An Example

In our person object, access to the data forename is supplied through the access operations set forename() and get forename().

Coding Data Hiding

The following code demonstrates a class containing some data that is hidden:

class Counter
{
  private int Count;

  public Counter()
  {
    Count = 0;
  }

  public void setCount( int newVal )
  {
    Count = newVal;
  }

  public int getCount()
  {
    return Count;
  }
}

This piece of code is also encapsulated, showing that you can have encapsulation without data hiding, but you cannot have data hiding without encapsulation.

C# Tutorial - Scope

posted Jun 28, 2011, 7:12 PM by magic stone

When using variable within a control structure, the variable only has scope with the curly brackets that it is declared between. Once the structure has finished, the variable goes out of scope and cannot be used anymore.

Examples of this are a do…while loop:

int i = 0;
do
{
  // j only has scope within the loop
  int j = 2;
  Console.WriteLine( “j = ” + j);
  i++;
}
While( i < 10 )
// j is no longer in scope

or a for loop:

for( int i = 0; i < 10; i++ )
{
  // j only has scope within the loop
  int j = 2;
  Console.WriteLine( “j = ” + j);
}
// j is no longer in scope

Defining Class Scope

class ScopeExmaple
{
  private void methodA()
  {
    _a = 2;
  }

  private void methodB()
  {
    _a = 3;
  }

  private int _a = 0;
}

A variable with class scope does not have to be declared before any method that uses it. The compiler sorts this out at compile time.

Defining Local Scope

private void methodA()
{
  int _a = 0;

  for( int i = 0; i < 10; i++ )
  {
    _a = 2;
    Console.WriteLine( “a = ” + _a);
    _a = _a + 2;
  }
}

In the above example, the local variable is declared before it is used. However, if we were to declare the variable after it is used as in class scope, then a compile time error will occur. This is shown in the next example.

private void methodA()
{
  for( int i = 0; i < 10; i++ )
  {
    // The compile time error will occur here as the variable has
    // not been declared yet.
    _a = 2;
    Console.WriteLine( “a = ” + _a);
    _a = _a + 2;
  }

  int _a = 0;
}

C# Tutorial - Even More on Classes

posted Jun 26, 2011, 11:15 PM by magic stone

C# allows a single class to be split across several files, through the use of the keyword partial. Partial classes do not make any logical difference to the compiler, as during compile time, it simply groups all of the various parts of the partial class and treats them as a single entity.

Why use Partial Classes?

Partial classes allow for a clean separation of business logic (implementation code) and the user interface (designer code). The UI code can be hidden away from the developer by the IDE, as the developer would access this code through the properties window.

Partial classes can also allow large classes to be separated into smaller manageable sections. The benefit of this is twofold; firstly the code becomes less cumbersome to navigate and second, multiple developers can work on a single class at the same time without the need for later merging of files within a source control application.

On top of this, by naming the partial class files with appropriate names, debugging of code becomes easier because you can jump quicker to an area of functionality.

Naming Files

Naming files containing a partial class becomes an important issue. Names should include the name of the class that is being defined as well as an indication of which aspects of the class are being defined in that file.

Visual C# Express splits any control or form into two files using the partial class implementation when you add one to your project. For example, when you add a new Form to your project, the code that you edit is called Form1.cs, and the code that is created by the IDE is called Form1.Designer.cs. Both files contain the same class, but use the partial keyword.

If for instance you create a class that has a lot of properties, then you may name the file myClass.Properties.cs wheremyClass is the name of the class within the file.

A Word of Warning

If a class ends up being split over many files, it may be time to stop and rethink whether the class would benefit from refactoring and taking advantage of some inheritance.

Coding Partial Classes

As an example to demonstrate the use of partial classes, we will break the Person class into private and public areas.

Anything public can be held in one file.

Person.cs
public partial class Person
{
  // Constructor
  public Person()
  {
  }

  // Methods
  public void setSurname( string aSurname )
  {
    _surname = aSurname;
  }

  public string getSurname()
  {
    return _surname;
  }
}

Anything private can be held in another file.

Person.Private.cs
partial class Person
{
  // Attributes
  private string _forename;
  private string _surname;
  private string _address;
  private int _age;
  private bool _gender;
  private string _dateOfBirth;
  private int _telephoneNumber;
  private int _NINumber;
}

Note

Both parts of the class must reside in the same namespace.

C# Tutorial - Overloading Constructors

posted Jun 26, 2011, 11:14 PM by magic stone

Each class can have more than one constructor, allowing the class to be built taking different information. This can be shown easier with and example. Let us look at the Person class, by making a simple change we can call the parent class constructor through the use of the base keyword.

public Person() : base()
{
  _address = null;
}

If we wanted to create a new Person object by passing a name to it, we can add a second constructor.

public Person( string surname )
{
  _surname = surname;
}

If we wanted to create a new Person object by passing it a date of birth, then we could add a third constructor.

public Person( DateTime dob )
{
  _dateOfBirth = dob;
}

Each of these new constructors can call the default constructor of the Person object, just like calling the base class constructor, but by using the this keyword instead.

public Person( string surname ) : this()
{
  _surname = surname;
}

public Person( DateTime dob ) : this()
{
  _dateOfBirth = dob;
}

Copy Constructors

A great use of overloading the constructor is to create a copy constructor, one that takes a copy of another object of the same type.

public Person( Person p )
{
  this.surname = p.surname;
  . . .
}

Example of Overloading Constructors

This is a great example of overloaded constructors.

public class Loader
{
  public Loader(string fileName, XmlNameTable nameTable)
      :this(new FileStream(fileName,FileMode.Open),nameTable){}
  public Loader(Stream stream, XmlNameTable nameTable)
      :this(new XmlTextReader(stream,nameTable)){}
  public Loader(string fileName):this(fileName, new NameTable()) {}
  public Loader(Stream stream):this(stream,new NameTable()){}
  public Loader(XmlReader xmlReader)
  {
    //actual constructor code goes here
  }
}

There are five constructors here which do different things.

  • If the class is created using the first constructor from the top:

    public Loader(string fileName, XmlNameTable nameTable)

    It makes a call to the next constructor:

    public Loader(Stream stream, XmlNameTable nameTable)

    Which makes a call to the final constructor:

    public Loader(XmlReader xmlReader)
  • If the class is created using the second constructor from the top:

    public Loader(Stream stream)

    A call to the final constructor is made:

    public Loader(XmlReader xmlReader)
  • If the class is created using the third constructor from the top:

    public Loader(string filename)

    A call to the first constructor from the top is made, followed by the first sequence.

  • If the class is created using the fourth constructor from the top:

    public Loader(Stream stream)

    A call to the second constructor from the top is made, followed by the second sequence.

  • If the class is created using the fifth constructor from the top, nothing else is called.


C# Tutorial - More on Classes

posted Jun 26, 2011, 11:13 PM by magic stone

Every class has the same defining layout:

[access-modifier] class [identifier] [:base-class]
{
  class-body
}

Where:

  • The access-modifier is optional. If you do not define one, then the method is defaulted to public, because a class cannot be private.

  • The keyword class identifies the type of the object.

  • The [identifier] is the name of the class being declared.

  • The [:base-class] tag allows a class to inherit from another class. Inheritance is discussed later.

  • The class-body contains all of the code that is associated with an object.

Constructors

When a class is declared as in the following code, we only say that we want to have an instance of the class in our program. We have not yet created the class in program memory.

Person Paul;

To do this we must instantiate an instance of the class, this is done using the new keyword, as in the following code:

Person Paul = new Person();

You can see that after the new keyword we called a method with the same name as the class. This is called its constructor. By calling this constructor, memory is allocated for the class, and we can now use it in our program, as in the next code sample.

Person Paul = new Person();
String surname = "Smith";
Paul.setSurname( surname );

A constructor is a method that is invoked upon instantiation of a class. In C# these are known as "instance constructors". An instance constructor is a member that implements the actions required to initialize an instance of a class. A constructor is invoked when you use the new operator, or use the various methods of reflection to create an instance of a class.

Defining the Constructor

Every constructor has the same defining layout:

[access-modifier] constructor_name (parameters)
{
  // constructor body
}

Where:

  • The [access-modifier] can be privatepublicprotected or internal.

  • The constructor_name of a constructor must be the same as the name of the class.

A constructor can take zero or more arguments as parameters. A constructor with zero arguments (that is no-arguments) is known as a default constructor. A class can have more than one constructor, by giving each constructor a different set of parameters. This gives the user the ability to initialise the object in more than one way.

The constructor body can be used to initialise the object into a known starting state.

Writing the Constructor

In, general, a constructor’s access modifier is public, this is because the class that is creating an instance of this class, needs to be able to access the constructor of the class.

public Person()
{
  . . .
}

Destructors

Each class also requires a destructor, this is the code that is called to clean up the object when it has been finished with. However, if you do not provide one, then the Garbage Collector will deal with freeing up the memory for you. Any object that you create in the class, should be deleted from the class as a general rule of thumb.

A destructor is defined pretty much in the same way as a constructor, but has a tilde (~) in front of the method name.

public ~Person()
{
  . . .
}

Everything Else

Apart from the constructor and destructor, the class body can contain as many attributes and methods as required. However, if a class is getting too large to work with, think about logically splitting it into smaller classes, or into smaller files using partialclasses.

1-10 of 18