What is an instance variable or memeber variable in C#?
In C#, an instance variable (also known as a member variable) is a variable that is defined within a class and is accessible to all of its member functions. An instance variable holds a separate value for each instance (or object) of the class.
When you create an instance of a class, memory is allocated for each of its instance variables, and each instance variable is initialized to its default value (which depends on its data type). You can then set the value of an instance variable using the dot notation, which specifies the instance followed by the name of the variable:
class clsPerson {
public string name; // an instance variable named "name"
public int age; // an instance variable named "age"
Public static void Main(){
ClsPerson person1 = new clsPerson();
person1.name = "Alice";
person1.age = 25;
}
}
In this example, we define a class named "Person" that has two instance variables named "name" and "age". We then create an instance of the clsPerson class named "person1" and set the values of its instance variables using the dot notation.
Instance variables are useful because they allow you to store state information within an object, which can then be accessed and manipulated by its member functions. They also make it possible to create multiple instances of a class, each with its own set of values for the instance variables.
No comments:
Post a Comment
If you have any query kindly let me know.