Next

Static Field

In C# a field normally is assigned on a per instance basis, with a unique value for each object instance of the class. Sometimes it is useful to have a single value associated with the entire class. This type of field is called a static field.

Static Methods

A method may also be declared static. A static method can be called without instantiating the class. An example we have already seen is the Main in a class, which the runtime system is able to call without instantiating an object. The Main method must always be static.

In C# the key difference between a class and a struct is that a class is a reference type and a struct a value type. A class must be instantiated explicitly using new. The new instance is created on the heap, and memory is managed by the system through a garbage collection process.

Enumeration Types

An enumeration type is a distinct type with named constants. Every enumeration type has an underlying type, which is one of the following.

Enumeration

An enumeration type is defined through an enum declaration.

Example 1

In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to int and assigned to int variables.

// keyword_enum.cs
// enum initialization:
using System;
public class EnumTest
{
   enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

   public static void Main()
   {
      int x = (int) Days.Sun;
      int y = (int) Days.Fri;
      Console.WriteLine("Sun = {0}", x);
      Console.WriteLine("Fri = {0}", y);
   }
}

Output

Sun = 2
Fri = 7

Notice that if you remove the initializer from Sat=1, the result will be:

Sun = 1
Fri = 6

Example 2

In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.

// keyword_enum2.cs
// Using long enumerators
using System;
public class EnumTest
{
   enum Range :long {Max = 2147483648L, Min = 255L};
   public static void Main()
   {
      long x = (long) Range.Max;
      long y = (long) Range.Min;
      Console.WriteLine("Max = {0}", x);
      Console.WriteLine("Min = {0}", y);
   }
}

Output

Max = 2147483648
Min = 255

Reference Types

A variable of a reference type does not directly contain its data but instead provides a reference to the data stored in the heap. In C# there are following kinds of reference types:

Reference type has a specific value null, which indicates the absence of an instance.

Strings

The relational operators like = = and = ! operators check if the object references are the same, not whether the contents of the memory locations referred to are the same. However, the String class overloads these operators, so that the textual content of the strings is compared.

 

 

 

 

 

 

 

 

 

 

 

Hosted by www.Geocities.ws

1