Why is a string a reference type but behaves differently than other types of links?

We know that a string is a reference type, so we have

string s="God is great!"; 

but in the same note, if I declare a class, they say Employee, which is a reference type, so why does the piece of code below not work?

 Employee e = "Saurabh"; 

2 How do we actually determine if a type is a reference type or a value type?

+4
source share
5 answers

This code will work if you had an implicit conversion from string to Employee . Basically, a string literal is of type string - that is, its value is a reference to the string (and interned in it). You can assign a value of one type to a variable of another type if there is a conversion between the two types - either user-defined or built-in. In this case, there is no conversion from string to Employee , therefore, an error.

Unlike some other answers, the types do not have to be the same - for example, this is normal:

 object x = "string literal"; 

This is great because there is an implicit conversion of links from string to object . You can also write:

 XNamespace ns = "some namespace"; 

because there is an implicit conversion from string to XNamespace .

To answer the second question: 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. This excludes pointer types that are slightly different :)

+14
source

Since they are not of the same type, if you define a TypeConverter, then this will work.

http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

+4
source

Link types cannot be assigned unless they are of the same type (this is known as type safety). The first example works because you assign a string literal to a variable of type System.String . The second example does not work because you are assigning a string literal to a variable of type Employee . The types must match or be assigned from right to left in order to carry out the assignment of values.

+2
source
 Employee e = "Saurabh"; 

will not work simply because they are of different types.

+2
source
 object x; x = new Employee(); x = "Hello World!"; 
+2
source

Source: https://habr.com/ru/post/1304271/


All Articles