Head First C# Logo

Converting Head First Java Concepts and Code to C#

Chapter 4

Page 79-82:  Encapsulation

Java: get/set methods

private int size;
public int getSize()
{
return size;
}

public void setSize (int s)
{
size = s;
}

In this example size is the private variable, and s is the public variable that is passed to the setSize method.  The setSize method then assigns the value of the public variable s to the private variable size.
C#: The same syntax can be used in C#.....download the code for the C# version of  GoodDog.cs.

Be sure to see the example below of achieving the same goal of using encapsulation,  but by using C# properties.
Note: The general concept of using get/set methods to access fields in Java and C# is the same:  get/set methods are used to access fields, where a field is defined as a variable in a class (oversimplified explanation). get/set methods are sometimes called accessor methods, or accessors.

Here is a C# example of an additional way to implement get/set methods to access field values using a concept called properties.   

private int size;

public int s 
{
get
{
return size;
}

set
{
size = value;
}
}

Here is the full C# example using properties,  based on the GoodDog class from page 82.  GoodDogProperties.cs