Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string is a reference type, but behaves differently from other reference types?

Tags:

string

c#

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?

like image 301
TalentTuner Avatar asked Nov 29 '22 11:11

TalentTuner


1 Answers

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 :)

like image 108
Jon Skeet Avatar answered Dec 07 '22 22:12

Jon Skeet