public struct Employee
{
public int EmpID;
public string Name;
public string Address;
}
using System;
namespace ConsoleApplication1
{
public struct Employee
{
public int EmpID;
public string empName;
private string Address;
public Employee(int ID,string name, string add)
{
EmpID = ID;
empName = name;
Address = add;
}
public void ShowData()
{
Console.WriteLine("Employee ID="+EmpID);
Console.WriteLine("Employee Name=" + empName);
Console.WriteLine("Employee Address=" + Address);
}
}
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee(10,"Raj","USA");
obj.ShowData();
Employee emp;
// error, must initialize first
// Console.WriteLine("Employee Name=" + emp.empName);
Console.ReadLine();
}
}
}
using System;
namespace ConsoleApplication1
{
struct StructValueType
{
public int x;
}
class Program
{
static void Main(string[] args)
{
StructValueType obj1;
StructValueType obj2;
obj1.x = 10;
obj2.x = 20;
Console.WriteLine("obj1.x = {0}, obj2.x = {1}", obj1.x, obj2.x);
obj1 = obj2;
obj2.x = 30;
Console.WriteLine();
Console.WriteLine("obj1.x = {0}, obj2.x = {1}", obj1.x, obj2.x);
Console.ReadLine();
}
}
}
using System;
namespace ConsoleApplication1
{
struct propertyStruct
{
private int intVar ;
public int initValue
{
get
{
return intVar;
}
set
{
if (value>0)
intVar = value;
}
}
public void DisplayValue()
{
Console.WriteLine("Value is: {0}", initValue);
}
}
class Program
{
static void Main(string[] args)
{
propertyStruct obj = new propertyStruct();
obj.initValue = 25;
obj.DisplayValue();
Console.ReadLine();
}
}
}
Class | Structure |
---|---|
Class is a reference type | Structure is value type |
Object stored on the heap. | Stored on the stack, and behave like simple data type. |
Class can inherit the another class | Structure does not support the inheritance. |
Class can have the all types of constructor | Supports parameterized constructors only. |
Supports destructors also. | Does not support destructors. |
The member variable of class can be initialized directly. | You cannot initialize instance field directly. |
Class can be declared as abstract | You cannot mark structure as abstract. |
class object cannot be created without using the new keyword MyClass obj = new MyClass(); | Structure object can be created without using the new keyword. MyStruct obj; |