Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

From the author of

Object Members

Besides methods and fields, C# has other class members, such as properties, indexers, and events. A property is sometimes called a smart field; it has a get accessor to customize value retrieval and a set accessor to customize setting the value. Here's an example of a property:

   private short foo;

   public short Foo
   {
     get 
     {
        return foo;
     }
     set
     {
        foo = value;
     }
   }

The previous code could be used like this (assuming that the property is a member of MyClass):

   MyClass.Foo = 25;

   Short myField = MyClass.Foo;

And here's an example of an indexer, which enables a class to provide array-like semantics.

   private ArrayList junk = new ArrayList();

   public this[int index]
     {
     get 
     {
        return junk[index];
     }
     set
     {
        junk[index] = value;
     }
   }

The previous code could be used like this (assuming that the property is a member of MyClass):

   MyClass[5] = "somestring";

   string myString = MyClass[2];

Indexers and properties don't look like any of Java's syntactical constructs.

It would be difficult for C# to mimic Java with overloaded operators such as these:

   public static MyClass operator+(MyClass bar1, MyClass bar2)
   {
     // some implementation
   }

That's especially true because Java doesn't have overloaded operators.

  • + Share This
  • 🔖 Save To Your Account