Structure is an value type, Then why don't compiler gives any error when string is declared within struct
Why below written code doesn't gives error even when string is a reference type.
public struct example
{
public int a;
public string name;
};
public void usestruct()
{
example objExample= new example();
MessageBox.Show(objExample.name);
}
EDIT
Modifying Jon Answer, I have few more Questions.
public struct Example
{
public int a;
public string name;
}
class Test
{
static void Main()
{
//Question 1
Example t1 = new Example();
t1.name = "First name";
Example t2 = t1;
t2.name = "Second name";
Console.WriteLine(t1.name); // Prints "First name"
Console.WriteLine(t2.name); // Prints "Second name"
Console.WriteLine(t1.name); // What will it Print ????
//Question 2
Example t1 = new Example();
t1.name = "First name";
Console.WriteLine(sizeof(t1)); // What will it Print ????
// I think it will print 4 + 4 bytes.
//4 for storing int, 4 for storing address of string reference.
//Considering
//int of 4 bytes
//Memory Address of 4 byte
//Character of 1 byte each.
//My collegue says it will take 4+10 bytes
//i.e. 4 for storing int, 10 bytes for storing string.
}
}
开发者_开发百科
How many bytes will second case take.
The struct just contains a reference to a string. Why would that cause a problem? A reference is just a value. When you copy the structure's value (e.g. with assignment, or passing it to a method) the reference will be copied too. Note that if you change the value of the field in one copy of the struct, that won't change the value in a different copy:
using System;
public struct Example
{
public int a;
public string name;
}
class Test
{
static void Main()
{
Example t1 = new Example();
t1.name = "First name";
Example t2 = t1;
t2.name = "Second name";
Console.WriteLine(t1.name); // Prints "First name"
Console.WriteLine(t2.name); // Prints "Second name"
}
}
If Example
were a class instead, these would both print "Second name" as the values of t1
and t2
would be references to the same instance.
This isn't specific to strings, either - any reference type will work.
However, I would strongly advise against creating mutable structs or exposing public fields.
精彩评论