What are properties and indexer?

Answer Posted / uday

Properties are not like variables, rather they are calling
methods. They dont be allocated memory like variables.
They(get,set accessors) will be called automatically when
we assigne value or refer the value.
class ProperyCls
{
string name;
public string Name
{
get
{
return name;
}
set
{
Console.WriteLine("In Set method the value
is "+value);
name = value;
}
}
}

class Program
{
static void Main(string[] args)
{
ProperyCls pObj = new ProperyCls();

//Here the set method will be automatically
called
pObj.Name = "Hello";

//Here the get method will be called
automatically
Console.WriteLine("In get method the value is "
+ pObj.Name);

Console.ReadKey();

}
}

Indexers are different in the context when i create
multiple instances of the class and assign properties for
each of the instances. Indexers can be defined with "this"
keyword.
class ProperyCls
{

public int this[int i]
{
get
{
return 20;
}
set
{
Console.WriteLine("In set the value is " +
value + "at index" + i);
}
}
}


class Program
{
static void Main(string[] args)
{
ProperyCls pObj = new ProperyCls();

pObj[1] = 10;
pObj[2] = 30;

Console.WriteLine("In get method the value
returned is " + pObj[1]);
Console.ReadKey();

}
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How to implement a singleton design pattern in c#?

472


How Do You Convert A Value-type To A Reference-type?

520


What is an object pool in .net?

649


What is Implicit conversion in C#?

557


What is the resgen.exe tool used for?

522






What is hashtable c#?

469


What is difference between private and static constructor?

462


What is distribute by in hive?

533


Is namespace necessary in c#?

489


How to handle exceptions that are raised in a component?

584


What is variable and its classification?

526


Is stringbuilder faster than string concatenation c#?

443


What is the syntax for calling an overloaded constructor within a constructor?

532


What happens during the process of boxing?

596


How do you remove white spaces from a string?

491