In the following program if data type is object, GetType() method returning data type is assigned value data type.
If object obj4 = new object(); then only returning data type is System.Object.What is the reason for that?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int value = 5;
object obj1 = 12;
object obj2 = "Scarborough";
object obj3 = 'A';
object obj4 = new object();
Console.WriteLine(value.GetType());
Console.WriteLine(obj1.GetType());
Console.WriteLine(obj2.GetType());
Console.WriteLine(obj3.GetType());
Console.WriteLine(obj4.GetType());
Console.ReadKey();
}
}
}
/*
System.Int32
System.Int32
System.String
System.Char
System.Object
*/
Loading
Posted Sep 5, 2013, 11:09 AM
VulpesPosted Sep 5, 2013, 8:06 AM
This is why, if you don't give them an explicit value, fields have the following values by default:
numeric value types - 0
bool - false
char - '\0'
all reference types - null
because these values correspond to 'all bytes zero'.
The Employee class doesn't actually have any fields and so you'd expect, on the face of it, that it wouldn't require any memory to be allocated on the heap.
However, all objects have some overhead (at least 8 bytes) and, if there are no fields, the CLR will allocate a minimum of 1 byte memory as a place-holder because there needs to be an address where the fields would otherwise start for technical reasons.
Posted Sep 5, 2013, 7:29 AM
VulpesPosted Sep 5, 2013, 7:25 AM
Unless it is overridden in the Employee class, the ToString() method will simply return the name of the type i.e. 'Employee' here.
Posted Sep 5, 2013, 7:16 AM
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int myInteger = new int();
Employee myAssistant = new Employee();
Console.WriteLine(myInteger);
Console.WriteLine(myAssistant);
Console.ReadKey();
}
}
}
class Employee { }
/*
0
Employee
*/
VulpesPosted Sep 4, 2013, 5:26 PM
Posted Sep 4, 2013, 4:00 PM
1.You are notifying the compiler that you will use the identifier myAssistant.
2.new operator is allocating computer memory.
When declaring like int myInteger = new int(); Please tell me what will happen behind the screen.
VulpesPosted Sep 4, 2013, 3:34 AM
Clearly:
obj1 refers to an int (or System.Int32),
obj2 refers to a string (or System.String),
obj3 refers to a char (or System.Char), and
obj4 refers to an object (or System.Object) because a new object is created and then a reference to it is assigned to obj4.