Thursday, October 13, 2011

Properties-


Destructor are actually responsible for deallocation of memory used by objects but in managed languages deallocation is taken care by garbage collector for which destructor are not required, whereas in some situation we may be using any unmanaged resource like files, database etc. which will not be under control of garbage collector, in such scenario we use these destructors for managing those unmanaged resources.  
  
Properties: - If at all a class contains any values in it that should be accessible outside of the class. Access to those values can be provided in two different ways –
  • By storing the value in public variable access to the value can be given where anyone can get the value or set with a new value.

public  class Show
{
public int x = 100;
}
……………………….
Show obj = new Show ();
int a = obj x ;                               // Getting the value
int.x = 200;                                  // Setting the value

  •  By storing the value in a private variable also access to the value can be given by defining a property on that variable, where we can provide the access to the value in three different ways.

  1. Both get and set access (read | write property)
  2. only get access (Read only property)
  3. only set access (Write only property) 

   Syntax 
[<modifiers>]<type> <name>
{
[get {- stmts}]  // get Accessor
[set {- stmts}]  // Set Accessor
}

The code which is present in the Get block is executed whenever we try to capture the value of property

Eg:-
string str = “Hello”;
int len = str.Length;

The code under set box gets executed whenever we are trying to assign in new value to the property
Console.BackgroungColor = ConsoleColor.Blue; 

-          If the property is defined with both get and set blocks it is a read | write property.
-          If defined only with get block, it is a read only property.
-          If defined only with a set block it is a write only property.


No comments: