Learn Object Oriented Programming Using C#: Part 1

  1. Object Oriented Programming Using C#: Part 2
  2. Object Oriented Programming Using C#: Part 3
  3. Object Oriented Programming Using C#: Part 4
  4. Object Oriented Programming Using C#: Part 5
  5. Object Oriented Programming Using C#: Part 6
  6. Object Oriented Programming Using C#: Part 7
  7. Object Oriented Programming Using C#: Part 8
  8. Object Oriented Programming Using C#: Part 9
  9. Object Oriented Programming Using C#: Part 10

Introduction 

C# is totally based on Object Oriented Programming (OOP). First of all, a class is a group of similar methods and variables. A class contains definitions of variables, methods etcetera in most cases. When you create an instance of this class it is referred to as an object. On this object, you use the defined methods and variables.

Step 1. Create the new project with the name "LearnClass" as shown below.

LearnClass

Step 2. Using "Project" -> "Add Class" we add a new class to our project with the name "FLOWER".

Project

Step 3. Now add the following code in the FLOWER class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LearnClass
{
    class FLOWER
    {
        public string flowercolor;
        public FLOWER(string color)
        {
            this.flowercolor = color;
        }
        public string display()
        {
            return "Color of the flower : " + this.flowercolor;
        }
    }
}

In this example, we have created the class FLOWER. In this class, we declared one public variable flower color. Our FLOWER class defines a constructor. It takes a parameter that allows us to initialize FLOWER objects with a color. In our case we initialize it with the color yellow. The Describe() method shows the message. It simply returns a string with the information we provided.

Step 4. Insert the following code in the Main module.

using System; 
namespace LearnClass
{
    class Program
    {
        static void Main(string[] args)
        {
            FLOWER flow;
            flow = new FLOWER("YELLOW");
            Console.WriteLine(flow.display());
            Console.ReadLine();
        }
    }
}

Console

Classes

Note. Method name FLOWER and class FLOWER are the same name but the method is a constructor of the class. (We will discuss that topic in detail later on.)


Similar Articles