Syntax of variables in C#.NET
Syntax of Variables & Fields
Variables are used to
store values. More technically, a variable binds an object (in the general
sense of the term, i.e. a specific value) to an identifier (the variable's
name) so that the object can be accessed later.
string
strTitle = "Variables & Fields in C#";
Console.WriteLine(name);
Fields,
sometimes called class-level variables, are variables associated with classes
or structures. An instance variable is a field associated with an instance of
the class or structure, while a static variable, declared with the static
keyword, is a field associated with the type itself. Fields can also be
associated with their class by making them constants (const), which requires a
declaration assignment of a constant value and prevents subsequent changes to
the field.
Each
field has a visibility of public, protected, internal, protected internal, or
private (from most visible to least visible)
So,
in C# we have 4 types of variables
1.
Instance Variables
2.
Class Variables
3.
Variables
4. Parameters
Instance and Class variables are called Fields.
Instance
Variables
These are where the variables belong to class
but are not static. Whenever we create a instance, that instance has its own
variables.
Commonly
in C# such variables have a Getter and Setter; The getter is a method that
allows us to read value and setter is a method that allows to set value.
class Student{
public
string name;
public
string name{
get{
return
name;
}
set{
name=value;
}
}
public
int SID;
public
string Course;
}
Class
Variables
These
are variables are static when declare, so whenever a new instance is made then
those variables become non static.
These variables are also known as static variables.
All
the instances will read from the same variables.
Example:
public class Student
{
public static float stdFee = 10500;
}
Local
Variables
These variables are declared inside of methods, not in a class. So it may be that you are using local variables to store a value from another class.
Example
public class Student
{
public static float stdFee = 10500;
public void displayMessage()
{
int repeat =4; // local variables
for(int
i =0; i<=4; i++)
{
Console.WriteLine(“Hi,Welcome
to Local Vriables Demo”);
}
}
}
A parameter is used to pass objects into a method. The method can use these variables to assist in its behaviors.
Example
public class Student
{
public string courseTitle = “C#”;
public string getcourseTitle()
{
return courseTitle;
}
// here we are passing coursename parameter to the function
to set course title..this is parmeter variable and only uses inside of method
for its behaviour.
public void setcourseTitle(string coursename)
{
this.courseTitle = coursename;
}}
Comments
Post a Comment