4. Properties
Properties are named members of classes, structures, and
interfaces. Member variables or methods in a class or
structures are called Fields.
Properties are an extension of fields and are accessed using
the same syntax. They use accessors through which the
values of the private fields can be read, written or
manipulated.
Properties do not name the storage locations. Instead, they
have accessors that read, write, or compute their values.
For example, let us have a class named Student, with
private fields for age, name, and code. We cannot directly
access these fields from outside the class scope, but we can
have properties for accessing these private fields.
5. Example
using System;
namespace Properties
{
class Student
{
private string code = "N.A";
private string name = "not known";
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
6. set
{
code = value;
}
}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
7. public override string ToString()
{
return "Code = " + Code + ", Name = " + Name;
}
}
class ExampleDemo
{
public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting code and name of the student
s.Code = "001";
s.Name = "Zara";
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
}
8. Indexers
Indexer Concept is object act as an array.
Indexer is an object to be indexed in the
same way as an array.
Indexer modifier can be private, public,
protected or internal.
The return type can be any valid C#
types.
Indexers in C# must have at least one
parameter. Else the compiler will
generate a compilation error.
10. set
{
range[indexrange] = value;
}
}
}
/* The Above Class just act as array declaration using this pointer */
class childclass
{
public static void Main()
{
ParentClass obj = new ParentClass();
/* The Above Class ParentClass create one object name is obj */
obj[0] = "ONE";
obj[1] = "TWO";
obj[2] = "THREE";
obj[3] = "FOUR ";
obj[4] = "FIVE";
12. Difference
Properties Indexers
Identified by its name. Identified by its signature.
Accessed through a simple name
or a member access.
Accessed through an element
access.
Can be a static or an instance
member.
Must be an instance member.
A get accessor of a property has
no parameters.
A get accessor of an indexer has
the same formal parameter list as
the indexer.
A set accessor of a property
contains the implicit value
parameter.
A set accessor of an indexer has
the same formal parameter list as
the indexer, in addition to the
value parameter.
13. References
Inspiration from Prof. Nitin R Patel
Notes of .NET
Textbook of .NET
Images from Google Images
Some my own Knowledge