Hi, I have the following example:
public class Material
{
public class Compuesto
{
public const int Peso = 33; // El peso del compuesto siempre es el mismo.
}
public int GetPesoCompuesto()
{
return Compuesto.Peso;
}
}
And the code Main()
:
public static void Main()
{
Material Mat = new Material();
Console.WriteLine("Peso del compuesto: " + Mat.GetPesoCompuesto()); // Funciona, retorna: 33
Console.WriteLine("Peso del compuesto: " + Mat.Compuesto.Peso); // Error.
Console.WriteLine("Peso general: " + Material.Compuesto.Peso); // Tambien funciona.
}
My question is, Why can I access the constant Peso
without instantiating the class in any variables, i.e. shouldn't the constant only be defined when I instantiate its class?
What would be the point of having to instantiate the class if the value would always be the same.
Variables and properties are only accessed when you instantiate the class because the value you assign can be different from instance to instance.
On the other hand, with a constant this does not happen, no matter how many instances you create, the value will be the same, that is why it can be accessed directly with the class name
Constants (C# Programming Guide)
You will see that constants can only have simple types such as int, string, short, etc, but you cannot create a const of another class or object, this is because these data types can be changed as they are types by reference.
In the link comment: