reference types in instantiated objects

D

DS

I've got a question about how I can go about nesting a reference type in
an object of an instantiated class alongside value types. This may seem
a bit vague so I'll give an example:

public class Cow
{
private string farm;
private int brandNumber;
public Cow()
{
farm = "Old MacDonald";
brandNumber = 0;
}
public string Farm
{
get { return farm; }
set { farm = value; }
}
public int BrandNumber
{
get { return brandNumber; }
set { brandNumber = value; }
}
}

then elsewhere...
Cow milk = new Cow();
milk.BrandNumber = 57;
Cow beef = milk;
//beef.BrandNumber = 95;
now here's what I want: I need them to both share the same Farm name so
that when the farm is changed for either it changes for all. This will
happen as this stands because "Cow beef = milk;" point to the same
place; unfortunately the brand number is not independent like this...

The trick is I need them to have independent BrandNumbers which means I
really need to declare it as "Cow Beef = new Cow();", but then I don't
have them sharing a reference to the same Farm. I cannot use a static
for the Farm because elsewhere I may have other Cows in another farm.

How can I do this in C#? Is there a way to change the farm value type to
a reference type?

Thanks a bunch in advance
-Dan
*apologies to the vegetarians/vegans, no cows were harmed in the
creation of this ;-)
 
T

Truong Hong Thi

I suggest you create a class, e.g. CowFarm

public class CowFarm
{
private string name;
// omit constructors and properties
}

public class Cow
{
private CowFarm farm;

// omit constructors and properties
}

To make them share a farm:
cow1.Farm = cow2.Farm;

To change name that affect both cows:
cow1.Farm.Name = "Mac2";
 
G

Guest

conceptually, i prefer to do it in the following flavour IMO

public class Farm {
List<Cow> cows;
//...
}

public class Cow {
Farm farmOfTheCow;
public Cow(Farm farm) {
}

}

regards
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top