Fields and Property in .net

Friday, 27 May 2016

Fields and Property in .net


A field is a variable that is declared directly in a class or struct.  Generally, we should use fields only for variables that have private or
protected accessibility.Fields should be kept private to a class and accessed via get and set properties. Data that your class exposes to client
code should be provided through methods, properties and indexers. By using these constructs for indirect access to internal fields, you can restrict
against invalid input values.
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.Properties expose fields, that means
it enable a class to expose a public way of getting and setting values, while hiding implementation. Properties provide a level of abstraction allowing


Use property procedures when:
• You need to control when and how a value is set or retrieved.
• The property has a well-defined set of values that need to be validated.
• Setting the value causes some perceptible change in the object's state, such as an IsVisible property.
• Setting the property causes changes to other internal variables or to the values of other properties.
• A set of steps must be performed before the property can be set or retrieved.
• Need to log all access for a field.
Use fields when:
• The value is of a self-validating type. For example, an error or automatic data conversion occurs if a
        value other than True or False is assigned to a Boolean variable.
• Any value in the range supported by the data type is valid. This is true of many properties of type Single         or Double.
• The property is a String data type, and there is no constraint on the size or value of the string.

Mainly we are using property because of accessing Private fields from out side the class and restrict the invalid input from client.

The main difference between Fields and Property is

                           Property                
     Fields
Properties may run for a very long time and may even throw exceptions          
Fields are fast and will never throw exceptions
Properties may return a different value for each call   
Fields always return the same value (except the issue with multiple threads)
An example to clear the basic of fields and Property

public class Myclass
{
public string classnmae; // This is a public fields Of Myclass
}

public class CallCls
{
    public static void main()
    {
       Myclass M = new Myclass();
       M.classnmae; = null ; // here Name can't be null
    }

}

So to restrict the user input from the client we will use property here

public class Myclass
{
Private string _classname; // This is a Private fields Of  Myclass
   public void setClassName(string Name)
   {
       if(string.IsNullOrEmpty(Name))
       {
         throw new exception("Class Name  should not be NULL");
       }
       this.Name = _classname;
    }
    public int getClassName()
    {
     if(string.IsNullOrEmpty(this._classname))
       {
          return "No Name";
       }
     else
      {
        return this._classname;
      }

     }


}

public class CallCls
{
    public static void main()
    {
       Myclass M = new Myclass();
       M.setClassName = null ; // It will throw the exception
    }

}


Different types of properties
Properties can be divided into three categories read-only, write-only, and read-write properties.


Read-Only Property

A read-only property allows you to only retrieve the value of a field. To create a read-only property, you should define the get accessor.

  class Example
   {
   string name;
   public string Name
   {
   get { return name; }
   }

Write-Only Property

A write-only property allows you to only change the value of a field. To create a write-only property, you should define the set accessor.
  class Example
   {
    string name;
    public string Name
    {
     set{ name = value; }
    }

   }
Read-Write Property

A read-write property allows you to write and read the value of a field. To create a read-write property, you should define the set and get accessors.

  class Example
  {
   string name;
   public string Name
   {
     get { return name; }
     set { name = value; }
   }
  }


Auto-implemented property

Automatic properties have support for default values much like fields.


class Medication
{
    public int Quantity { get; set; } = 30; // Has default value.
}

To make an auto-implemented property read-only or write-only, you need to specify both get and set accessors.
public int ReadOnly { get; private set; }
public int WriteOnly { private get; set; }

Static property
You can also declare a property static. To make a static property you must ensure that the backing store field is also static. Typically, a static property is used to make a singleton class.
public class Singleton
{
 private static Singleton instance = new Singleton();
 private Singleton() { }

 public static Singleton GetInstance
 {
 get { return instance; }
 }
}


Abstract property

An abstract property declaration does not provide an implementation of the property accessors. It leaves the accessors implementation to derived classes. Abstract properties are declared with in a abstract class or interface.
public abstract class Details
{
 public abstract string Name{ get; set;}

}

class Admin: Details
{
 private string name;

 // Override Name property
 public override string Name
 {
 get { return name; }
 set { name = value; }
 }
}
public interface IDetails
{
 string Name { get; set; }

}

class Student : IDetails
{
 private string name;

 // implement Name property
 public string Name
 {
 get { return name; }
 set { name = value; }
 }
}