Object Oriented Programming Style in C# (OOP)
Submitted by Yorkiebar on Thursday, August 28, 2014 - 08:06.
Introduction:
This tutorial is on how to use OOP (Object Oriented Programming) in C#.What is OOP?
OOP is when you are able to run multiple instances of one class or form at one time without them colliding in to one another. I will give you an example; Let's say that we have a 'person' class, with the variables to hold that person's name and age. Without OOP, we could only have one person. But, with OOP, we could create multiple instances of this 'Person' class, and give them all their own names/ages.Class:
First create a new C# project and create a new class named 'Person.cs'. In that class, create a variable to hold their name...- string name = string.Empty;
- int age = -1;
Form:
Now that we have our class with our variables, we are going to go back to our Form1/Main.cs file of the project we just created and create two instances of the 'Person.cs' class. We do this the exact same way as any other object or variable, we first write the data type 'Person' followed by the object/variable name, then set it equal to a new instance of the class, like so... Next we are going to set some details for each of them. Set personA's name to 'Josh' and age to '21'...- personA.name = "Josh";
- personA.age = 21;
- personB.name = "Derick";
- personB.age = 45;
Output:
Finally we are going to output the details for each of them to show that they are using the same class, but not conflicting variables...- MessageBox.Show(personA.name + " " + personB.name + Environment.NewLine + personA.age.ToString() + " " + personB.age.ToString());
Finished!
Full source code... Main.cs/Form1:- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace JayPabsOOP
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- personA.name = "Josh";
- personA.age = 21;
- personB.name = "Derick";
- personB.age = 45;
- MessageBox.Show(personA.name + " " + personB.name + Environment.NewLine + personA.age.ToString() + " " + personB.age.ToString());
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace JayPabsOOP
- {
- class Person
- {
- public string name = string.Empty;
- public int age = -1;
- }
- }
Add new comment
- 167 views