«

»

Jul 12

C# .Net Basics: Classes

CSharpTypesSmClasses

A class is a user defined object or type construct that allows you to group together fields, properties and methods into a custom type that behaves in a consistent way.  A class is a reference type; when an instance of a class is instantiated, an object reference is returned to the calling function, not the object itself.  Once the object is created, it is kept in memory until all references to it go out of scope.  At that time, the CLR (Common Language Runtime) marks it for garbage collection.  Classes support inheritance, with some exceptions, a class can only inherit from one other class (base class) and can implement more than one interface.

The access level of the class is declared first.  The access modifiers are public and internal.

Access Modifier Accessibility
public Unrestricted
internal limited to the current assembly (defalut)

Classes are declared by using the ‘class’ keyword followed by the name of the class.

public class Classname
{
    //fields, properties, events and methods
}

Static Classes

If a class is declared as Static, only one instance of it can exist in memory and it is always loaded and available.  Structurally, static classes and the same as non-static classes, the only difference is that they cannot be instantiated.  This means you cannot create an new instance; meaning you cannot use new to create a reference to a static class, instead you access it directly by its class name and the name of a function in it. (See Example Below)

A static class is guaranteed to be loaded and initialized when your code is running, you do not have to do anything special to access it.  It remains in memory for the lifetime of your application.  A characteristic of a static class is that it cannot utilize any internal instance fields.  A static class can only contain static members and it may have a private, static (not instance), constructor.  They also are sealed and cannot be inherited nor can they inherit from any class except Object.

//static class declaration
public static class Utilities
{
    //static function declaration
    public static string SayHello(string name)
    {
        string RetVal;
        //do something
        return RetVal;
    }
 }
 
 
 
 //Call SayHello from external code
 strResp = Utilities.SayHello(strName);
 

Classes can also be configured as Generic classes, most commonly for collection types, which is a separate topic.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>