






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
How to create your own classes in programming, which can store variables (data members) and functions (methods). The benefits of using methods include avoiding repeat code, promoting software reuse, and promoting good design practices. A template for defining methods and discusses access control using public and private modifiers. It also covers class constructors and using methods as accessors and mutators.
Typology: Study notes
1 / 10
This page cannot be seen from the preview
Don't miss anything!
Before starting
Defining a Method
MessageBox.Show(calculateDensity("Alaska", 627000, 591000)); MessageBox.Show(calculateDensity("Hawaii", 1212000, 6471)); }
private void showHelpMessage() { MessageBox.Show("If this was a real program, a " + "help message would be displayed."); } private void button1_Click(object sender, EventArgs e) { showHelpMessage(); }
public partial class Form1 : Form { Random rnd = new Random(); ... private void button1_Click(object sender, EventArgs e) { int diceroll; diceroll = RollDice(); Console.WriteLine(diceroll); } }
Class Variables – Data Members
class Money { public int dollars; public int cents; }
private void button1_Click(object sender, EventArgs e) { Money m1 = new Money(); Money m2 = new Money(); m1.dollars = 3; m1.cents = 40; m2.dollars = 10; m2.cents = 50; Console.WriteLine(m1.dollars + " " + m1.cents); Console.WriteLine(m2.dollars + " " + m2.cents); }
private void button1_Click(object sender, EventArgs e) { Money m1 = new Money(); m1.dollars = 3; // Legal, dollars is public m1.cents = 40; // ILLEGAL, cents is private }
Class Constructors
class Money { private int dollars = 0; private int cents = 0; // This constructor invoked if we create // the object with no parameters public Money() { dollars = 1; cents = 0; } // This constructor invoked if we create the object with // a dollar and cent value public Money(int inDollars, int inCents) { dollars = inDollars; cents = inCents; }
// Method to return the value as a string // It would be better to add "override" but // we will discuss that later public string toString() { return("$" + Convert.ToString(m_dollars)
private void button2_Click(object sender, EventArgs e) { Money m1 = new Money(); Money m2 = new Money(5, 50); Console.WriteLine(m1.ToString()); Console.WriteLine(m2.ToString()); }
Methods as Accessors and Mutators