Problem: C # properties; Result: C # Properties

Source: Internet
Author: User
Tags access properties

C # Properties

Property: Get {//Read Property Code} set {//write Property Code}
public class Person
{
private string name;
public string Name
{
Get{return name;}
set{Name=value;}
}
}
Property can ignore get or set accessors, but not both.
The set accessor contains a hidden parameter, value, which contains values that are passed from the customer code.
It is best to use the same name for public properties and their underlying types, because the connections between them will be clear.

Fields use CamelCase (XXXXX), such as dateOfBirth, and properties use Pacalcase (XXXXX), such as dateOfBirth. Some developers prefer to use underscores at the beginning of a field, such as _name, and attributes should also be named using nouns.

C # provides protection for a field in a class by reading and writing fields with property attributes rather than directly reading and writing.

The properties are divided into three different types according to the types that can be accessed:

I. Read/write properties

The read/write property is a property with the Get () and set () accessors.

Syntax: [access modifier] Data Type property
{
get{};
set{};
}

Two. read-only properties

Only a Get () accessor property is called a read-only property.

Syntax: [access modifier] Data Type property name
{
get{};
}

Three. Write-only properties

Only the set () accessor property is called a write-only property, and the write-only property is not recommended.

Syntax: [access modifier] Data Type property name
{
set{};
}
Example:

Using System;

Namespace Example1
{
Class Student
{
#region/*** Property ***/
<summary>
Name
</summary>
private string name;
public string Name
{
Get
{
return name;
}

Set
{
if (value.length<40)
{
Console.WriteLine ("Student name cannot be less than 4!");
Return
}
Name=value;
}
}
#region

static void Main (string[] args)
{
Student student=new Student ();
Student. Name=console.readline ();
}
}
}

Attribute (property)
-Fully embodies the encapsulation of the object: not directly manipulate the data content of the class, but access through the accessor, that is, the use of get and set to read and write the value of the property, on the other hand, you can also control the access properties of the data (can also be achieved by adding ReadOnly keywords to the ordinary domain).
-Design principle: attributes encapsulate the operation of the domain. Make the domain you want to access private, set or access the domain through the get and set operations in the properties.
-the property cannot be passed as a reference type or as an output parameter.
The-get method has no arguments, and the set method has an implied parameter, value. In addition to the abstract properties that are used with the abstract modifier, there is only a semicolon ";" in the execution body of each accessor, and the get accessor for all other properties reads the value of the property through return, and the set accessor sets the value of the property by value.
-An indirect way to access the properties of an object (indirect call to get, set method): Object. property = value (call set), variable = object. property (call Get).
-In the access declaration of the property:
Only the set accessor indicates that the property is write-only.
Only the get accessor indicates that the property is read-only.
Both a set accessor and a get accessor indicate that the attribute is readable and writable.
private string S_filename;
public string Filename
{
Get
{
return s_filename;
}//get
Set
{
if (S_filename!=value)
{
S_filename = value;
}//if
}//set
}//filename
}

L Comparison of properties and fields:

Ø attribute cannot use Ref/out type parameter

Ø attribute must be assigned before use

Properties must be assigned before they are used, for example:

Time lunch;

Lunch. Hour = 12;//error, lunch not initialized

Properties vs. functions

L Similarity Point

Ø all include execution code

Ø all can have access modifiers

Ø all can have virtual, abstract, override modifier

Ø can be used in the access port

L Different points

Ø attribute can only have get/set statements

Ø attribute can not be void type

Ø attribute cannot use parameter

Ø property cannot use [] parameter

Ø attribute cannot use parentheses
public int Hour

{

...

Set
{

if (Value < 0 | | value > 24)

throw new ArgumentException ("value");

hour = value;

}



The properties of a class are called smart fields, and the indexer of a class is called a smart array. Because the class itself is used by the Count group,
This is the name of the indexer, and the indexer has an indexed parameter value. Cases:
Using System;
Using System.Collections;

Class MyListBox
{
Protected ArrayList data = new ArrayList ();
public Object This[int IDX]//this as indexer name, IDX is index parameter
{
Get
{
if (idx >-1 && idx < data. Count)
{
return DATA[IDX];
}
Else
{
return null;
}
}
Set
{
if (idx >-1 && idx < data. Count)
{
DATA[IDX] = value;
}
else if (idx = data. Count)
{
Data. ADD (value);
}
Else
{
Throws an exception
}
}
}
}

}

Write a C# code that runs more efficiently, more robust, and easier to maintain, whenever possible.

use the property as muchas possible instead of the data member (field ).

private int Property1
public int Property1
{
Get
{
return property1;
}
Set
{
if (value>1)//Check here
property1= value;
Else
Property1=1;
}



Instance properties, readable writable
public int Strcount
{
Get
{
return m_strcount;
}
Set
{
if (Value>m_strcount)
{
Strarray = new String[value];
for (int i=0;i<value;i++)
{
Strarray[i] = String.Format ("String no.{0}", i);
}
M_strcount = value;
}
}
}

private static string m_strname = "MyClass";
A static property, read-only
public static string ClassName
{
Get
{
return m_strname;
}
}


Class B
{
Private A _a;
Public A Item
{
Get
{
if (_a=null)
_a=new A ();
return _a;
}
Set{_a=value;}
}
}

Differences in properties and fields in C #

The difference between a property and a field

In C #, we have a very free, unrestricted access to public fields, but in some cases we may want to limit the values that can only be assigned to a field, or to require fields to be read-only or write-only, or to change some other state of an object when changing a field, which cannot be done by a single field. Then there is the attribute, which contains two blocks: Set and Get,set block are responsible for the writing of the property, the get block is responsible for the property read work. There are a few other things you can do in two blocks, such as verifying that the assigned value meets the requirements in set and deciding whether to assign a value. When one of the pieces is missing, the property is only readable or writable, and the properties in the set and get blocks must have one, because a property that cannot be read and cannot be written is meaningless.

Class MyClass

{

Private string name;

public string Name

{

get {return Name;}

set {Name=value;}

}

}

(1) Attributes are guaranteed to be secure, and when not used in this class, it is guaranteed that property names can be used to avoid

Use the name of the field.

(2) The set and get functions of a property can limit some of the functions of a field for some purpose.

Such as:

private int a=0;public int a{get{return THIS.A;}         set {if (value >= 0 && value <=) This.a=value; else throw new Exception ("The range of values is not valid.     "); }} (3) property does not have the ability to store data, the data exists in the field, so only modifying the field's data can change the data, modifying the value of the property is useless.

Problem: C # properties; Result: C # Properties

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.