Suppose you have a C# class
instance (like a StringBuilder
). It can be used as an object because it inherits from the object class
—all classes do.
We can pass any type as an object parameter—the cast is performed automatically (implicitly) by the compiler. Object is an important feature of the C# type hierarchy.
Any C# type can be used as an object. Each class
is derived from the base class
object. Each reference is both an object and its derived types.
StringBuilder
type.using System; using System.Text; class Program { static void Main() { // Use an object reference. object val = new StringBuilder(); Console.WriteLine(val.GetType()); } }System.Text.StringBuilder
Next this program introduces a method that receives an object type parameter. It shows how to use objects as arguments to functions.
string
variable is assigned a reference to a literal string
. This is passed as an object type to the Test method.Test()
checks its parameter against null
. It then uses the is
-cast to test the most derived type of the object.string
) expression as true. The second 2 calls will match (value is int
).using System; class Program { static void Main() { // Use string type as object. string value = "Dot Net Perls"; Test(value); Test((object)value); // Use integer type as object. int number = 100; Test(number); Test((object)number); // Use null object. Test(null); } static void Test(object value) { // Test the object. // ... Write its value to the screen if it is a string or integer. Console.WriteLine(value != null); if (value is string) { Console.WriteLine("String value: {0}", value); } else if (value is int) { Console.WriteLine("Int value: {0}", value); } } }True String value: Dot Net Perls True String value: Dot Net Perls True Int value: 100 True Int value: 100 False
Object.Equals
This method compares the contents of objects. It first checks whether the references are equal. Object.Equals
calls into derived Equals
methods to test equality further.
object.Equals
. It uses 2 strings.string
literal. The second is a character that is converted to a string
with ToString
.string
literal "a" and the result of ToString
are in different memory locations. Their references are thus not equal.Equals
is the same as object.ReferenceEquals
, but it goes further. With ReferenceEquals
the derived equality method is not used.using System; class Program { static void Main() { // Equals compares the contents (and references) of 2 objects. bool b = object.Equals("a", 'a'.ToString()); Console.WriteLine(b); // ReferenceEquals compares the references of 2 objects. b = object.ReferenceEquals("a", 'a'.ToString()); Console.WriteLine(b); } }True False
The object type has some complexities. Value types cause no heap allocations. But without the heap allocation, the object cannot exist.
We examined the object type. We can use an object as an argument. We can receive any type as an object type in the formal parameter list.