In C++ I could do something like this
class Person
{
House * myhouse;
}
class House
{
std::vector<Person*> members;
}
How can I do a similar thing in C#?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Instead of fields here i’m using properties, in particular, automatic properties.
This is both for being cleaner, exposing a field to the outer world is usually less clean than exposing a property, and also because i can control in this way how people can access to the properties for read and for write. In this example, property Members is public for read but private for write, I initialize it in the constructor.
In C# there is not the concept of objects allocated in stack, objects are always allocated in heap.
This means classes are always reference types and a variable of type List is a reference to an object of type List, like a pointer is in C++.
For this reason you need to use the new operator to allocate it, or the default value will be null.
Of course, as you know, in C# there is the garbage collector, so you don’t need to delete the object.
In C# there are also value types, basic types like int, float, double and struct are value types, and they works in a different way indeed.
Arrays and strings are still reference types (classes).
Also note that in C# class fields are initialized by default in the constructor to 0, each type you can think of will be initialized with 0, so, a pointer will be null, a float will be 0.0f, a struct will be a struct with all fields set to 0. Like a calloc in C.
There is however another totally different approach possible.
We can use the base class Collection and make the MyHouse property totally transparent and safe: we set it when we change the collection, this technique is used often.