Monday 5 November 2012

C# Objects, Classes, Structs and Inheritance



As a developer it is important to structure you code intelligently, C# is no different. As a flexible and powerful object oriented language is critical that you understand its object structures to enable you to design and implement best practice applications. Sadly many developers lack the basic overview or have some gaps in their knowledge which can limit their conceptualization and object oriented design structures. 

Please bear with me as it’s a bit of a lengthy post, the source code is available for download
if you want to dive into the code itself.

Structures and Classes

The two main custom object types used in C# is Struct’s and Classes, this with enumerations and delegates all have one root type/base class, the System.Object class. Basically these are the main reusable groupings of sub elements; this structures define their relationship and interaction in the context of the container object (In this case a Struct or a Class).

  •  Introduction to Structs
This is an easy object structure to implement, very fast and good to represent lightweight objects that will be used often. (When to use Struct’s and some more reading)

Syntax: [attributes] [modifiers] struct identifier [:interfaces] body [;]


  • Introduction to Classes


This is the most used custom object structure that can be used to represent basic to very complex object structures, dependencies, behaviors and inheritances.

Syntax: [attributes] [modifiers] class identifier [:base-list] { class-body } [;]

Example of a basic student class and implementation:






Some main differences between Classes and structures
  •  Structs are value types while classes are reference types
  • How they are allocated in memory (Heap and Stack)
  • Constructors have different rules, Struct can’t create parameterless constructor (You cannot use a struct until all the fields are initialized) and can be instantiated without using the New operator.
  • Structs does not have inheritance like Class objects. It inherits only from the System.Object class although it can implement interfaces.

Closer look into the standalone class structure

A class is a composite container of elements and behaviors. It is important to understand the syntax and layout to be able to create the best representative object structure of what you want to accomplish. Some might even look familiar coming from Struct’s. Be sure to follow the standard naming convention.

Some common concepts:


Access Modifier
Description
The most permissive level, there are no restrictions on accessing them
The least permissive level, access only allowed from within the body of a class or struct.
This allows access from within the class and any subsequent derived classes
Accessible within the assembly that it is declared in.
*Check out Internals exposed to other assemblies (InternalVisibleTo) very useful to expose internal methods to unit testing assemblies as example.
Protected Internal
Accessible to assembly it was declared in or from another where the class declaration derives from the original class. In essence allowing access for where either Protected or Internal criteria is met.

 

Main areas a class can consist of and tips on each:
 

These are class methods that are executed when an object of a given type is created
*Check out overloading and Object Initializer
Destructors are used to destruct instances of classes.
These are attributes describing a class, properties are members with method like capability
* Nullable value types (Using ? and ??)
*Check out Auto Properties
Methods describe logically grouped behavior of a class or struct
*Look at Out Parameters
This resemble array like properties except that their accessors take parameters
Events enable class/object to notify classes/objects when something of interest occur
Flexible method containers that live can live in variables or declared inline

Some important keywords to control access and scope
* Check out the Singleton pattern (Single class instance across all sessions)
Classes & Structs



 A more complete class example:






Basic Inheritance:
  • Partial Classes (A class structure allowing it to be constructed from multiple locations)
  • Interfaces (Describe a group of related functionalities using only their signatures)

More advance object relationships and inheritance
  • Polymorphism
Using inheritance classes can have multiple types and implementations. Polymorphism is the ability to structure inheritance so that class implementations can take multiple forms.





Key-Word
Description
new
Used for Member Shadowing. Using new in an inherited class will allow you to create another method with the same name as that already exists higher up in the hierarchy (Regardless if the upper method was declared as virtual or not). Please note this is in the context of methods.
*Keep in mind that both methods exist, and can be executed depending on how the object is casted.
This marks a method as replaceable in a class that derives from the class that implemented the virtual method.
This marks a method to replace a higher up method that was marked as virtual. Note that the original item cannot be executed.
This will stop the overriding of a specific method in lower inheritance. The provides the final unchangeable method downwards




Overloading methods
Use different parameter types and sequences as a signature to allow for different implementations of the same method.




  •  Abstract & Sealed Classes

The abstract keyword enables you to create classes and class members that are incomplete; this base class defines the structure that the derived classes must align to. 

Note: Abstract classes cannot be instantiated.




*Note that the source code is available from GitHub.

No comments:

Post a Comment