Create a Class in C#

In this article we will explain about how to create a class and access its members outside the class.
  • 3353

We know that a class is the combination of data and functions that operate upon data in one entity. Classes in C# are defined using the class keyword followed by the name of the class. Class is like a built-in- data type which an be used to declare a variable of its type. Class keep the data secure inside it from outside the program. By default the access modifier of the class is internal which means that class can be access only in the application not outside the application.

using System;

 

namespace classexampl

{

    class Program

    {

        static void Main(string[] args)

        {

            sample ss = new sample();

            ss.setdata(2,4);

            ss.displaydata();

            Console.ReadLine();

        }

    }

    class sample

    {

        private int i, j;

        public void setdata(int ii,int jj)

        {

            i = ii;

            j = jj;

        }

        public void displaydata()

        {

            Console.WriteLine("The value of i and j is {0} {1}",i,j);

        }

    }

}

Output:

image1.jpg

Here we have declared a class sample. i and j are called data members of class sample. setdata() and displaydata() are called member functions or methods. The private written while declaring data members implies that they can be accessed only in the methods of class, not from the outside the class . On the other hand, the public keyword specifies that the methods can be accessed both from inside as well as outside the class.

The statement sample ss=new sample() creates an object of class sample and stores its address in ss. So to say, ss is a reference to the object. Methods of the class can be accessed only by using its reference. So, we have used ss to call displaydata() and setdata() methods.

Further Readings
 
You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.