Why string is a reference type, but behaves differently from other reference types?
We know that string is a reference type , so we have
string s="God is great!";
but on the same note if i declare class say Employee which is a reference type so why below piece of code does not work ?
Employee e = "Saurabh";
2- How do we actually determine if a type is a reference type or value ty开发者_Go百科pe?
That code would work if you had an implicit conversion from a string to an Employee
. Basically a string literal is of type string
- i.e. its value is a string reference (and an interned one at that). You can only assign a value of one type to a variable of another type if there's a conversion between the two types - either user-defined or built in. In this case, there's no conversion from string
to Employee
, hence the error.
Contrary to some other answers, the types don't have to be the same - for example, this is fine:
object x = "string literal";
That's fine because there's an implicit reference conversion from string
to object
. Likewise you can write:
XNamespace ns = "some namespace";
because there's an implicit conversion from string to XNamespace
.
To answer your second question: to see if a type in .NET is a value type or a reference type... struct
and enum
types are value types; everything else (class, delegate, interface, array) is a reference type. That's excluding pointer types, which are a bit different :)
Because they're not the same type, if you define a TypeConverter then that would work.
http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx
Reference types are not assignable unless they are of the exact same type (this is known as type safety). The first example works because you are assigning a string literal to a variable of the type System.String
. The second example does not work because you are assigning a string literal to a variable of the type Employee
. The types must match or be assignable from right to left for value assignment to work.
Employee e = "Saurabh";
will not work simply because they are of different types.
object x;
x = new Employee();
x = "Hello World!";
精彩评论