Articles → .NET → Property Vs Variable in C#

Property Vs Variable in C#






Difference 1




//  Read/Write variable 
public string readWriteVariable;

// Read only variable
public readonly string readOnlyVariable;

// Read/Write property
public string ReadWriteProperty {
  get;
  set;
}

// Read only property
public string ReadOnlyProperty {
  get {
    return string.Empty;
  }
}

// Write only property
public string WriteOnlyProperty {
  set {}
}



Difference 2




// Variable
List < string > names = GetNames();

// Property
private List < string > _names = null;
public List < string > Names {
  get {
    //  Lazy initialization
    if (_names == null)
      _names = GetNames();

    return _names;
  }
  set;
}



Difference 3




// No abstraction
public int voting_age;

public int VotingAge {
  get {
    // Abstraction
    if (voting_age < 18)
      return 18;
    else
      return voting_age;
  }
  set {
    voting_age = value;
  }
}



Difference 4




public interface ITest {
  // Valid
  int MyProperty {
    get;
    set;
  }
  //  int y; // Will give an error
}



Difference 5







Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, June 3, 2015

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250