Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Constructors, Structs,

and Enums
RHEA MAE L. PERITO, MSIS
SUBJECT INSTRUCTOR
Constructor
A method that is called when an instance of a
class is created.
Its purpose is to put an object in an early state.
Structure
public class Customer{

public Customer(){
}
}
Sample
public class Customer{
public string Name;

public Customer(string name){


this.Name = name;
}
}
Sample
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();


Constructor Overloading
public class Customer{
public Customer() {…}
public Customer(string name) {…}
public Customer(int id, string name){…}
}
Sample (Program.cs)
class Program
{
static void Main(string[] args)
{
var customer = new Customer(1,"John");
Console.WriteLine(customer.Id);
Console.WriteLine(customer.Name);
}
}
Sample (Customer.cs)
public class Customer
{
public Customer(int id, string name)
public int Id; {
this.Id = id;
public string Name;
this.Name = name;
public Customer()
{ }
}

}
public Customer(int id)
{
this.Id = id;
}
Structs
are essentially just small objects for related data.
Ex. Info about a person:
 Name
 Age
 eyeColor

- etc…
Sample
struct Person class Program
{
{
static void Main(string[] args)
public string name;
{
public string eyeColor;
Person Person1;
public int age; Person1.name = “James”;
} }
}
Enum
isa special "class" that represents a group of
constants (unchangeable/read-only values).
Sample 1
enum Level
{
Low,
Medium,
High
}
How to access
Level myVar = Level.Medium;
Console.WriteLine(myVar);
Sample 2 How to access
enum Months Months months = Months.February;
{ Console.WriteLine((int) months);
January, // 0
February, // 1 int x = 1;
March, // 2 Console.WriteLine((months) x);
April, // 3
May, // 4 Console.WriteLine(months.ToString());
June, // 5
July // 6
}

You might also like