Saturday 18 August 2018

C#: Instance variables

Instance variables are those which are associated with object. Person object, personA has instance variables height, weight, color, country.

Instance variables are also called member variables or fields.

Fields declaration syntax
modifier dataType variableName;

Field declaration composed of three components
1.   modifier is any one of public, private, protected, internal, protected internal.
2.   dataType is any primitive or reference type
3.   name of the variable

Example:
private int var;

Access Modifiers (public, private)
private : the field is accessible only within its own class.

For example, consider the class Person. I given private access to instance variables height, weight, color and country. So any method which is defined inside the class Person can able to access these variables, but you can't access outside the class.

public: If you declare any field using public modifier, then the field is accessible from outside of the class also.

Following is the complete working application.

Program.cs

using System;

class Person
{
    private float height, weight;
    private String color, country;

    public float getHeight()
    {
        return height;
    }

    public void setHeight(float height)
    {
        this.height = height;
    }

    public float getWeight()
    {
        return weight;
    }

    public void setWeight(float weight)
    {
        this.weight = weight;
    }

    public String getColor()
    {
        return color;
    }

    public void setColor(String color)
    {
        this.color = color;
    }

    public String getCountry()
    {
        return country;
    }

    public void setCountry(String country)
    {
        this.country = country;
    }

}

class Program
{

    static void printPerson(Person person)
    {
        Console.WriteLine("Color : {0}", person.getColor());
        Console.WriteLine("Country : {0}", person.getCountry());
        Console.WriteLine("Weight : {0}", person.getWeight());
        Console.WriteLine("Height : {0}", person.getHeight());
    }

    static void Main(string[] args)
    {
        Person person1 = new Person();
        person1.setColor("White");
        person1.setCountry("India");
        person1.setHeight(5.9f);
        person1.setWeight(67.5f);

        printPerson(person1);
    }

}

Output

Color : White
Country : India
Weight : 67.5
Height : 5.9





Previous                                                 Next                                                 Home

No comments:

Post a Comment