TOC

This article is currently in the process of being translated into Spanish (~26% done).

Clases:

Fields

Uno de los bloques de construcción más básicos es un campo. Es como una variable, como hablamos previamente, pero definido en el nivel de clase en lugar de en el nivel método. La diferencia es bastante importante y tiene que ver con el concepto de alcances, que decide desde dónde puede ser accedida una variable: Una variable local (definida dentro de un método) solo puede ser accedida desde este método específico, mientras que un campo de clase puede ser accedido desde todos los métodos de una clase e incluso desde métodos de otras clases si la visibilidad lo permite.

En otras palabras, la diferencia entre una variable y un campo es más o menos dónde se declara. Una variable a nivel de clase se conoce como un campo, mientras que una variable a nivel de método generalmente se conoce como variable.

Fields are often declared near the top of the class and their visibility are often set to private (we'll discuss visibility later in this chapter). It could look like this:

public class FieldsSample
{
	private string name;
	....

We now have a class-level variable called "name", which can be accessed from all methods of this class. It can't be accessed from outside the class, but only because we have marked it as private. You are free to declare your fields as protected if you want to access them from derived classes or even public if you want to access them from anywhere, but keep in mind that the recommended way of accessing fields from outside a class is through properties, which we'll discuss in the next article.

In our example above, or "name" variable doesn't have an initial value, meaning that you will have to assign something to it before you can use it. If you already know which value your field should start with, you can easily assign it at the same time as declaring it:

public class FieldsSample
{
	private string name = "John Doe";
	....

As an alternative, you can assign a value to a field in the constructor of the class. This will overwrite any value assigned to the field at the declaration point and will allow you to assign dynamic values.

As we talked about previously, members of a class can be accessed with the dot-notation, like "class.member". However, when we are accessing a member of the current class, we use the "this" keyword, like "this.member". Here's a more complete example where we declare a couple of fields and use them inside a method:

public class Fields1
{
	private string name = "John Doe";
	private int age = 42;

	public void Describe()
	{
		string description = this.name + " is " + this.age + " years old...";
		Console.WriteLine(description);
	}
}

In the Describe() method (and don't worry, we'll get to methods in one of the next articles) we declare a local variable called "description", with a value based on our two declared fields. The "description" variable is a great example of a variable which should always be a variable and never a field: It's temporary and only relevant to the method which uses it, where the fields could easily be relevant in other methods of the class.

Summary

Fields act a bit like global variables because they can be used to store data which can then be accessed from anywhere inside the class. They can be accessed from outside the declaring class as well, but normally, properties are used for this purpose. We'll talk about properties in the next article.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!