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 type?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With