int x = new int();
x = 120;
int y = new int();
y = x;
y = 130;
Console.WriteLine("x = " +x);
Console.ReadLine();
class Numbers
{
public int intVar;
}
class Program
{
static void Main(string[] args)
{
Numbers obj1 = new Numbers();
obj1.intVar = 30;
Numbers obj2 = new Numbers();
obj2 = obj1;
obj2.intVar = 40;
Console.WriteLine("Value = "+obj1.intVar);
Console.ReadLine();
}
}
Value Type | Reference Type |
---|---|
Stored on stack | Stored on heap |
Contains actual value | Contains reference to a value |
Cannot contain null values | Can contain null values |
Value type is erased on its own from stack when control goes out of scope. | It requires garbage collector to free memory. |
Memory is allocated at compile time | Memory is allocated at run time |
int intVar = 10; // intVar is a value type
object obj = intVar; // intVar is boxed
System.Console.WriteLine(intVar.ToString());
using System.Collections;
ArrayList list = new ArrayList(); // list is a reference type
int intVar = 10; // intVar is a value type
list.Add(intVar); // intVar is boxed
intVar = (int)list[0]; // list[0] is unboxed
System.Console.WriteLine(intVar.ToString());
static void Main(string[ ] args)
{
int ? intVar = null;
Console.WriteLine("intVar has value: " + intVar.Value);
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[ ] args)
{
int? intVar = null;
if (intVar.HasValue)
Console.WriteLine("intVar has value: " + intVar.Value);
else
{
Console.WriteLine("intVar has no value");
Console.WriteLine("intVar = "+intVar.GetValueOrDefault());
}
intVar = 35;
if (intVar.HasValue)
Console.WriteLine("intVar has value: " + intVar.Value);
else
Console.WriteLine("intVar has no value");
Console.ReadLine();
}
}
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int? firstVar = null;
int secondVar = 100;
if (firstVar < secondVar)
Console.WriteLine("intVar < secondVar");
else if (firstVar > 100)
Console.WriteLine("intVar > secondVar");
else if (firstVar == 100)
Console.WriteLine("intVar == secondVar");
else
Console.WriteLine("Could not compare null");
Console.ReadLine();
}
}
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int? firstVar = null;
int secondVar = 100;
if (Nullable.Compare<int>(firstVar, secondVar) < 0)
Console.WriteLine("firstVar < secondVar");
else if (Nullable.Compare<int>(firstVar, secondVar) > 0)
Console.WriteLine("firstVar > secondVar");
else
Console.WriteLine("firstVar = secondVar");
Console.ReadLine();
}
}
}