I would do so:
using static System.Console;
public class Program {
public static void Main(string[] args) {
Cliente cliente = new Cliente();
cliente.endereco.rua = "guaranesia";
WriteLine(cliente.endereco.rua);
}
}
class Cliente {
public string name{get; set;}
public string idade { get; set; }
public Endereco endereco = new Endereco();
}
class Endereco {
public string rua { get; set; }
public string bairro { get; set; }
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
Make the class work for you. Encapsulate the implementation. Make the consumer cleaner and don’t force him to be aware of how he should use the parts of the class. You used the tag encapsulation which shows that you understand that you should use this form, now you need to implement it like this. You should also consider making the field your own endereco
as a property.
In fact in a real class very likely you should have builders. Something like that:
using static System.Console;
public class Program {
public static void Main(string[] args) {
var cliente = new Cliente("João", "20", "Rua Torta", "Centro");
WriteLine(cliente.Endereco.Rua);
}
}
class Cliente {
public string Nome {get; set;}
public string Idade {get; set;}
public Endereco Endereco {get; set;}
public Cliente(string nome, string idade, string rua, string bairro) {
Nome = nome;
Idade = idade;
Endereco = new Endereco(rua, bairro);
}
}
class Endereco {
public string Rua {get; set;}
public string Bairro {get; set;}
//Note que não é preciso criar um construtor Endereco() já que ele não fará nada extra
//O compilador criará um para você
public Endereco(string rua, string bairro) {
Rua = rua;
Bairro = bairro;
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I believe that this type of code in a royal class could impair the readability of the code. After all initializing objects with very long constructors can make the code even legible. This way, I prefer to use Object Initializers to Constructors.
– Tobias Mesquita
I also prefer but I used more to show how it can be done, but I will edit to put the example you spoke.
– Maniero