Archive

Archive for July 15, 2008

Properties in .NET

Property in C#:

Property ? it is a special method that can return a current object?s state or set it. Simple syntax of properties can see in the following example:

public int Old 
{
   get {return m_old;}
   set {m_old = value;}
 } 
public string Name 
{
   get {return m_name;} 
}

Here are two types of properties. A first one can set or get field of class named m_old, and the second is read only. That?s mean it can only get current object?s state.

The significance of these properties is its usability. These properties need not be called with any function names like objectname.get or objectname.set etc., But they can be directly assigned the values or retrieve the values.

The VB .NET Syntax of declaring a property is as follows:-

Public Property X() As Integer
Get
     Return
x
End
Get
Set(ByVal Value As Integer
)
     x = value
End
Set
End Property

Enumerations in .NET

The enum keyword is used when you require a enumeration. A enumeration is a distinct type that consists of a set of named constants called the enumetor list. Every enumeration type has an underlying type which can be all integral times except that of a char type.Where:

Declaration syntax:

  • attributes (optional) – this is additional declarative information, look under index A for more information
  • modifiers (optional) – permissible modifiers include: new, public, protected, internal and private ( the 4 access modifiers)
  • base-type (optional) – underlying type for the storage allocated for each enumerator, any integral type except char (default is int)
  • enumerator-list – the enumerators identifiers which are seperated by commas (optionally including a value assignment)

Key Points:

The default underlying type of the elements in the enumeration is int as previously mentioned. The first enumerator begins at 0 by default and each enumerator following is increased by 1. Explicit casts are required to convert from enum type to an integral type.

enum Months {Jan, Feb, March, April,
May, June, July, August, Sept, Oct, Nov, Dec};

// same as above EXCEPT forced to start sequence
// from 1 instead of 0 (default)
enum Months2 {Jan = 1, Feb, March, April,
May, June, July, August, Sept, Oct, Nov, Dec};
   
public void Page_Load(object sender, EventArgs e)
{
    // notice the explicit cast required
    int x = (int) Months.Feb;
    int y = (int) Months.Oct;
   
    Response.Write(“
Feb is month #” + x);
    Response.Write(“
Oct is month #” + y);
   
    // sequence forced to start with 1 i.e Jan = 1 (in the declaration)
    x = (int) Months2.Feb;
    y = (int) Months2.Oct;
   
    Response.Write(“
Feb is now month #” + x);
    Response.Write(“
Oct is now month #” + y);
   

}

[attributes] [modifiers] enum identifier [:base-type] {enumerator-list};