I am with this doubt since I would like to know why it is not necessary to initialize an accumulator in vb.net
Module Module1
Sub Main()
Dim valor, suma As Integer
Do
Console.Write("Ingrese valor (0 pera finalizar):")
valor = Integer.Parse(Console.ReadLine())
suma = suma + valor
Loop While valor <> 0
Console.WriteLine(suma)
Console.ReadKey()
End Sub
End Module
In other languages like C or C# they ask you to assign/initialize it with a value but in VB.Net it doesn't seem necessary. Why?
Well, in C# you have to differentiate between "Fields" and "Local Variables". Fields do not need to be initialized, while local variables do. We see it in an example:
This example compiles perfectly, and
i
is initialized with the default value ofint
, that is0
However, the following example does not compile:
This is done to ensure the reliability of the application, and is fully explained in the C# language reference in section 5.3 Definitive Assignment
As for VB.Net, it is a language that has inherited certain habits from the original Visual Basic, among them the no need to initialize local variables. It is a language in which it is somewhat easier to shoot yourself in the foot, and therefore it is recommended to activate the
Option Strict
and optionsOption Explicit
, to prevent difficult problems to debug.Summarizing: Why is this so? Because when both languages were defined, it was decided that it should be like that, there is no need to give it much more thought. C# is a new language that has learned from the mistakes of previous languages, while VB.net had to make some concessions to make the transition from Visual Basic easier.
Very simple: all types have a default value with which they are initialized if a specific value is not indicated when declaring them.
In the specific case of
Integer
, this value is0
.