Suppose I have this setup:
Code:
public class Example
{
// it's a class
}
public class Helper
{
public void Foo(Example e)
{
// here
}
public static void Main(string[] args)
{
Helper h = new Helper();
Example myExample = new Example();
h.Foo(myExample);
}
}
Since Example is a class, and myExample is an instance of that class, myExample is a reference. When the Foo method gets hold of the argument passed in to it (i.e. where it's labelled 'here'), it's a
reference to the same myExample object that was created in the static Main.
Underneath, it just represents a memory location where all it's information is stored. The Foo method gets a copy of the same memory location.
Now suppose we have this:
Code:
public struct Example
{
// it's now a struct
}
public class Helper
{
public void Foo(Example e)
{
// here
}
public static void Main(string[] args)
{
Helper h = new Helper();
Example myExample = new Example();
h.Foo(myExample);
}
}
Now, since it's a struct, instead of being the memory location pointing to the object's data, it's the memory location of the data stored in the struct.
This time around, when we pass it in to the method (labelled 'here') we get a whole new copy of all the data, and underneath it's pointing to the memory location of this copied data.
Quote:
| Originally Posted by C_rookie
My question is, if you can store objects of different types inside a struct, as well as define functions and so on, how could a struct be a value type in the first place? |
If a struct 'store objects of different types' then it's only storing references to these objects, not the object's data themselves. The reference is a memory location plus a few other bits. The object being referred to in this way could be huge, but the reference to it is always the same size.