Sei sulla pagina 1di 2

Properties allow you to control the accessibility of a classes variables, and is the recommended way

to access variables from the outside in an object oriented programming language like C#.

A property is much like a combination of a variable and a method - it can't take any parameters, but
you are able to process the value before it's assigned to or returned.

A property consists of 2 parts, a get and a set method, wrapped inside the property:

private string color;

public string Color


{
get { return color; }
set { color = value; }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Get_Set
{
class access
{
// String Variable declared as private
private static string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}

public string Name //Creating Name property


{
get //get method for returning value
{
return name;
}
set // set method for storing value in name field.
{
name = value;
}
}
}

class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:\t");
// Accepting value via Name property
ac.Name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}

Program for record

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Employee


{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class Manager : Employee
{
private string name;
// Notice the use of the new modifier:
public new string Name
{
get { return name; }
set { name = value + ", Manager"; }
}
}
class TestHiding
{
static void Main()
{
Manager m1 = new Manager();
// Derived class property.
m1.Name = "John";
// Base class property.
((Employee)m1).Name = "Mary";
System.Console.WriteLine("Name in the derived class is: {0}", m1.Name);
System.Console.WriteLine("Name in the base class is: {0}", ((Employee)m1).Name);
}
}

Potrebbero piacerti anche