Accessing members of an object using C#

Now that you know how to create a class and its object using C#, in this tutorial you will learn how to access the data and functions of the object.  As we mentioned in the previous tutorials that C# is a purely object oriented programming language. Nothing can exist outside a class. So all the variable and functions you create are inside a class and you can access them using the object of the class.

How to access the members of an object

Suppose you have a class called Algebra with two data members X and Y and a function Sum. The Sum function will add the values of X and Y and return us the result back. Look at this class below

class Algebra  {        public Int X;      public int Y;      public int Sum()      {          return X + Y;      }    }

Now our goal is to create the object of the Algebra class, pass two integer values to X and Y variables, call the Sum function and get the result. Finally we will print the result on the Console window. Below is the code which you will write to do all this. We are writing the code in the Main function

static void Main(string[] args)  {              // Create object of the Algebra class              Algebra algebra = new Algebra();                // Set values of X and Y variables              algebra.X = 10;              algebra.Y = 20;                // Call the Sum function              int sum = algebra.Sum();                // Print the result              Console.Write(sum);  }

Read the comments in the above code to know what we are doing. See how we are using the dot ( . ) symbol with the object name to access the data members and functions of the object.

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp