Learn Object Oriented Programming Using C#: Part 1

Introduction to C# Classes

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 name "LearnClass" as shown below.

Classes1.jpg

Step 2

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

Classes2.jpg

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 flowercolor. 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();

        }

    }

 }

Classes3.jpg
Classes4.jpg


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.)

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    Learn
    View all