Predefined type reference type
C# supports two predefined reference types: object and string
name | .NET type | illustrate |
object | Root type, from which other types are derived (including value types) | |
string | Unicode string |
type
Many programming languages and hierarchies provide a root type from which other objects in the hierarchy are derived. C# and .Net are no exception. In C#, the object type is the final parent type, from which all built-in types and user-defined types are derived. In this way, the object type can be used for two purposes.
- You can use object references to bind objects of any specific subtype. For example, use the object type to box the value object in the stack and then move it to the heap. Object references can also be used for reflection. In this case, there must be code to handle objects of unknown types.
- The object class implements many general-purpose basic methods, including Equals(), GetHashCode(), GetType(), and ToString(). User-defined classes require overriding, an object-oriented technique, to provide alternative implementations of some of these methods. For example, when overriding ToString(), provide a method for the class to give the character hint of the class itself. If the class does not provide implementation code for these methods, the compiler will use the implementation code in the object type, and their execution in the class context may not be correct.
type
C# has the string keyword, which is converted to a .NET class under mask. With it, operations like string concatenation and string copying are simple.
string str1 = "Hello"; string str2 = "World"; string str3 = str1 + str2;
Although this is an assignment of a value type, string is a reference type. String objects are allocated on the heap, not the stack. therefore,When you assign a string variable to another string, you get two references to the same string in memory.. But there are some differences between the common behavior of string and reference types. For example, strings are immutable. Modifying one of the strings will create a new string object, while the other string will not change.