Can have - private fields, public properties, constructors and methods
using System;
//Object initializer syntax, introduced in c# 3.0
// can be used to initialize either a struct or a class
public struct Customer
{
private int _id;
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public int ID
{
get { return this._id; }
set { this._id = value; }
}
//Constructor
public Customer(int Id, string Name)
{
this._id = Id;
this._name = Name;
}
public void PrintDetail()
{
Console.WriteLine("Id = {0} && Name = {1}", this._id, this._name);
}
}
public class Program
{
public static void Main()
{
Customer C1 = new Customer(101, "Mark"); //using constructor
C1.PrintDetail();
Customer C2 = new Customer();
C2.ID = 102;
C2.Name = "John";
C2.PrintDetail();
Customer C3 = new Customer
{
ID = 103,
Name = "Rob"
};
}
}
========================
difference between classes and structs
using System;
public sealed class Customer // can't be used as a bass class
//public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
~Customer()
{
}
}
// structs are stored on stack, can't have destructors, can't have explicit parameter
// can't inherit from another class but can inherit from interface
// heaps are stored on heap, can have destructors, can have explicit parameter
// can inherit from another class and can inherit from interface
public class Program
{
public static void Main()
{
//int i = 0;
//if (i == 10)
//{
// int j = 20;
// Customer C1 = new Customer //need to be garbege collector
// {
// ID = 101,
// Name = "Mark"
// }; //destroyed j variable
//}
////value type...not copy value
//int i = 10;
//int j = i;
//j = j + 1;
//Console.WriteLine("i = {0}, j = {1}", i, j);
//Customer C1 = new Customer
//{
// ID=101, Name = "Mark"
//};
////reference type ... copy value
//Customer C2 = C1;
//C2.Name = "Mary";
//Console.WriteLine("C1.Name = {0} && C2.Name = {1}", C1.Name, C2.Name);
}
}