Студопедия
Новини освіти і науки:
МАРК РЕГНЕРУС ДОСЛІДЖЕННЯ: Наскільки відрізняються діти, які виросли в одностатевих союзах


РЕЗОЛЮЦІЯ: Громадського обговорення навчальної програми статевого виховання


ЧОМУ ФОНД ОЛЕНИ ПІНЧУК І МОЗ УКРАЇНИ ПРОПАГУЮТЬ "СЕКСУАЛЬНІ УРОКИ"


ЕКЗИСТЕНЦІЙНО-ПСИХОЛОГІЧНІ ОСНОВИ ПОРУШЕННЯ СТАТЕВОЇ ІДЕНТИЧНОСТІ ПІДЛІТКІВ


Батьківський, громадянський рух в Україні закликає МОН зупинити тотальну сексуалізацію дітей і підлітків


Відкрите звернення Міністру освіти й науки України - Гриневич Лілії Михайлівні


Представництво українського жіноцтва в ООН: низький рівень культури спілкування в соціальних мережах


Гендерна антидискримінаційна експертиза може зробити нас моральними рабами


ЛІВИЙ МАРКСИЗМ У НОВИХ ПІДРУЧНИКАХ ДЛЯ ШКОЛЯРІВ


ВІДКРИТА ЗАЯВА на підтримку позиції Ганни Турчинової та права кожної людини на свободу думки, світогляду та вираження поглядів



Контакти
 


Тлумачний словник
Авто
Автоматизація
Архітектура
Астрономія
Аудит
Біологія
Будівництво
Бухгалтерія
Винахідництво
Виробництво
Військова справа
Генетика
Географія
Геологія
Господарство
Держава
Дім
Екологія
Економетрика
Економіка
Електроніка
Журналістика та ЗМІ
Зв'язок
Іноземні мови
Інформатика
Історія
Комп'ютери
Креслення
Кулінарія
Культура
Лексикологія
Література
Логіка
Маркетинг
Математика
Машинобудування
Медицина
Менеджмент
Метали і Зварювання
Механіка
Мистецтво
Музика
Населення
Освіта
Охорона безпеки життя
Охорона Праці
Педагогіка
Політика
Право
Програмування
Промисловість
Психологія
Радіо
Регилия
Соціологія
Спорт
Стандартизація
Технології
Торгівля
Туризм
Фізика
Фізіологія
Філософія
Фінанси
Хімія
Юриспунденкция






Topic: Properties

Properties are named members of classes. 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 accessorsthrough which the values of the private fields can be read, written or manipulated. Properties do not name the storage locations. Instead, they have accessorsthat 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. The accessorof a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. For example:

 

// Declare a Code property of type string:

public string Code

{

get

{

return code;

}

set

{

code = value;

}

}

 

// Declare a Name property of type string:

public string Name

{

get

{

return name;

}

set

{

name = value;

}

}

 

// Declare a Age property of type int:

public int Age

{

get

{

return age;

}

set

{

age = value;

}

}

 

Example:

The following example demonstrates use of properties:

 

using System;

class Student

{

private string code = "N.A";

private string name = "not known";

private int age = 0;

 

// Declare a Code property of type string:

public string Code

{

get

{

return code;

}

set

{

code = value;

}

}

 

// Declare a Name property of type string:

public string Name

{

get

{

return name;

}

set

{

name = value;

}

}

// Declare a Age property of type int:

public int Age

{

get

{

return age;

}

set

{

age = value;

}

}

public override string ToString()

{

return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;

}

static void Main(string[] args)

{// Create a new Student object:

Student s = new Student();

// Setting code, name and the age of the student

s.Code = "001";

s.Name = "Zara";

s.Age = 9;

Console.WriteLine("Student Info: {0}", s);

//let us increase age

s.Age += 1;

Console.WriteLine("Student Info: {0}", s);

Console.ReadKey();

}

}

}

 

When the above code is compiled and executed, it produces the following result:

 

Student Info: Code = 001, Name = Zara, Age = 9

Student Info: Code = 001, Name = Zara, Age = 10

 

 

Abstract Properties

An abstract class may have an abstract property, which should be implemented in the derived class. The following program illustrates this:

 

using System;

public abstract class Person

{

public abstract string Name

{

get;

set;

}

public abstract int Age

{

get;

set;

}

}

class Student : Person

{

private string code = "N.A";

private string name = "N.A";

private int age = 0;

 

// Declare a Code property of type string:

public string Code

{

get

{

return code;

}

 

set

{

code = value;

}

}

 

// Declare a Name property of type string:

public override string Name

{

get

{

return name;

}

set

{

name = value;

}

}

 

// Declare a Age property of type int:

public override int Age

{

get

{

return age;

}

set

{

age = value;

}

}

public override string ToString()

{

return "Code = " + Code +", Name = " + Name + ", Age = " + Age;

}

public static void Main()

{

// Create a new Student object:

Student s = new Student();

// Setting code, name and the age of the student

s.Code = "001";

s.Name = "Zara";

s.Age = 9;

Console.WriteLine("Student Info:- {0}", s);

//let us increase age

s.Age += 1;

Console.WriteLine("Student Info:- {0}", s);

Console.ReadKey();

}

}

 

When the above code is compiled and executed, it produces the following result:

Student Info: Code = 001, Name = Zara, Age = 9

Student Info: Code = 001, Name = Zara, Age = 10

 




Переглядів: 142

Не знайшли потрібну інформацію? Скористайтесь пошуком google:

 

© studopedia.com.ua При використанні або копіюванні матеріалів пряме посилання на сайт обов'язкове.


Генерація сторінки за: 0.005 сек.