I'm starting to do my tests in C#
and I'm always running into the same problem.
When I create a class and I create several constructors, I always fail the constructor that does not contain parameters. Within the class, this constructor (the one that does not have parameters) constructs the object calling another constructor that if it receives parameters, the problem is that at a certain point the values of the parameters disappear. When I run the program in debug
mode I see that the code works until it reaches a point the value of the variables are lost.
I put the code:
class Password
{
private int Longitud;
private int Contraseña;
public Password()
{
Password Password = new Password(8);
}
public Password(int Longitud)
{
this.Contraseña = Generar(Longitud);
}
private int Generar(int Longitud)
{
Random aleatorio = new Random();
if (Longitud == 1)
{
return aleatorio.Next(0, 9);
}
else if (Longitud == 2)
{
return aleatorio.Next(0, 99);
}
else if (Longitud == 3)
{
return aleatorio.Next(0, 999);
}
else if (Longitud == 4)
{
return aleatorio.Next(0, 9999);
}
else if (Longitud == 5)
{
return aleatorio.Next(0, 99999);
}
else if (Longitud == 6)
{
return aleatorio.Next(0, 999999);
}
else if (Longitud == 7)
{
return aleatorio.Next(0, 9999999);
}
else if (Longitud == 8)
{
return aleatorio.Next(0, 99999999);
}
return -1;
}
public bool EsFuerte()
{
return Convert.ToString(Contraseña).Length > 5;
}
public void GenerarPassword(int Longitud)
{
this.Contraseña = Generar(Longitud);
}
public void MostrarPassword()
{
Console.WriteLine(Convert.ToString(Contraseña));
}
public int MostrarLongitud()
{
Longitud = Convert.ToString(Contraseña).Length;
return Longitud;
}
}
// Este funciona OK
Password pass1 = new Password(5);
// Este me decuelve parametros vacios
Password pass1 = new Password();
Example
If I build the object using the second constructor, the program works correctly for me and the value of the variables are the ones that have to be, whereas if I use the first one, the final result is not correct and the value of the variables is finished. losing for some reason (that will have its explanation but I do not know it).
It happens to me every time I create two constructors and one calls the other for abastecerse
of parameters that the user ignores.