Home > Articles > Programming > C#

This chapter is from the book


Section 4.2 Classes, Objects, Methods, Properties and Instance Variables

  • Methods perform tasks. Each method describes the mechanisms that actually perform its tasks. The method hides from its user the complex tasks that it performs.
  • The application unit that houses a method is called a class. A class may contain one or more methods that are designed to perform the class's tasks.
  • A method can perform a task and may return a result.
  • An instance of a class is called an object.
  • Each message sent to an object is a method call and tells that method to perform its task.
  • Each method can specify parameters that represent additional information the method requires to perform its task correctly. A method call supplies arguments for the method's parameters.
  • An object has attributes that are carried with the object as it's used in an application. These attributes are specified as part of the object's class. Attributes are specified in classes by fields.
  • An object has properties for accessing attributes. Properties contain get accessors for reading attributes and set accessors for storing into them.

Section 4.3 Declaring a Class with a Method and Instantiating an Object of a Class

  • Keyword public is an access modifier.
  • Every class declaration contains keyword class followed immediately by the class's name.
  • A method declaration that begins with keyword public indicates that the method is "available to the public"—that is, it can be called by other classes declared outside the class declaration.
  • Keyword void indicates that a method will not return any information when it completes its task.
  • By convention, method names begin with an uppercase first letter, and all subsequent words in the name begin with an uppercase first letter. This is called Pascal case.
  • Empty parentheses following a method name indicate that the method does not require any parameters to perform its task.
  • Every method's body is delimited by left and right braces ({ and }).
  • The body of a method contains statements that perform the method's task. After the statements execute, the method has completed its task.
  • When you attempt to execute an application, C# looks for a Main method to begin execution.
  • Typically, you create an object of a class to call the class's methods.
  • Object creation expressions begin with the new operator and create new objects.
  • To call a method of an object, follow the variable name with a member access operator (.), the method name and a set of parentheses containing the method's arguments.
  • In the UML, each class is modeled in a class diagram as a rectangle with three compartments. The top compartment contains the name of the class, centered horizontally in boldface. The middle compartment contains the class's attributes, which correspond to fields in C#. The bottom compartment contains the class's operations, which correspond to methods and constructors in C#.
  • The UML models operations by listing the operation name, followed by a set of parentheses. A plus sign (+) in front of the operation name indicates that the operation is a public operation in the UML (i.e., a public method in C#). The plus sign is called the public visibility symbol.

Section 4.4 Declaring a Method with a Parameter

  • Methods often require additional information to perform their tasks. Such additional information is provided to methods via arguments in method calls.
  • Console method ReadLine reads characters until a newline character is encountered, then returns the characters as a string.
  • A method that requires data to perform its task must specify this in its declaration by placing additional information in the method's parameter list.
  • Each parameter must specify both a type and an identifier.
  • At the time a method is called, its arguments are assigned to its parameters. Then the method body uses the parameter variables to access the argument values.
  • A method can specify multiple parameters in a comma-separated parameter list.
  • The number of arguments in the method call must match the number of required parameters in the method declaration's parameter list. Also, the argument types in the method call must be consistent with the types of the corresponding parameters in the method's declaration.
  • The UML models a parameter of an operation by listing the parameter name, followed by a colon and the parameter type between the parentheses following the operation name.
  • The UML does not provide types that correspond to every C# type. For this reason, and to avoid confusion between UML types and C# types, we use only C# types in our UML diagrams.
  • There's a special relationship between classes that are compiled in the same project. By default, such classes are considered to be in the same namespace. A using directive is not required when one class in a namespace uses another in the same namespace.
  • A using directive is not required if you always refer to a class with its fully qualified class name.

Section 4.5 Instance Variables and Properties

  • Local variables can be used only in the method in which they're declared.
  • A class normally contains methods that manipulate the attributes that belong to a particular object of the class. Attributes are represented as instance variables in a class declaration. Such variables are declared inside a class declaration but outside its method's bodies.
  • Each object (instance) of a class has a separate copy of each instance variable.
  • Most instance-variable declarations are preceded with the private access modifier. Variables, properties or methods declared with access modifier private are accessible only to methods (and properties) of the class in which they're declared.
  • Declaring instance variables with access modifier private is known as information hiding.
  • Properties contain accessors that handle the details of modifying and returning data.
  • Properties provide a controlled way for programmers to "get" (i.e., retrieve) the value in an instance variable and "set" (i.e., modify) the value in an instance variable.
  • A property declaration can contain a get accessor, a set accessor or both. The get accessor typically enables a client to read the value of a private instance variable. The set accessor typically enables a client to modify that instance variable's value.
  • After defining a property, you can use it the same way as you use a variable.
  • The default value for a field of type string is null.

Section 4.6 UML Class Diagram with a Property

  • We model properties in the UML as attributes, preceded by the word "property" in guillemets (« and µ). Using descriptive words in guillemets (called stereotypes in the UML) helps distinguish properties from other attributes.
  • A class diagram helps you design a class, so it's not required to show every implementation detail of the class. Since an instance variable that's manipulated by a property is really an implementation detail of that property, our class diagrams do not show instance variables.
  • private class members are preceded by the private visibility symbol (-) in the UML.
  • The UML represents instance variables and properties as attributes by listing the attribute name, followed by a colon and the attribute type.

Section 4.7 Software Engineering with Properties and set and get Accessors

  • Properties can scrutinize attempts to modify an instance variable's value (known as data validation), thus ensuring that the new value for that instance variable is valid.
  • Using properties would seem to violate the notion of private data. However, a set accessor can provide data-validation capabilities to ensure that the value is set properly; get and set accessors can translate between the format of the data used by the client and the format used in the private instance variable.
  • A benefit of fields over local variables is that all of a class's methods and properties can use the fields. Another distinction is that a field has a default initial value provided by C# when you do not specify the field's initial value, but a local variable does not.

Section 4.8 Auto-Implemented Properties

  • With an auto-implemented property, the C# compiler automatically creates a private instance variable, and the get and set accessors for returning and modifying the private instance variable.
  • Visual C# 2010 Express and Visual Studio 2010 have a feature called code snippets that allows you to insert predefined code templates into your source code. One such snippet enables you to insert a public auto-implemented property by typing the word "prop" in the code window and pressing the Tab key twice.
  • Pieces of the inserted code are highlighted for you to easily change the property's type and name. Press the Tab key to move from one highlighted piece of text to the next in the inserted code.
  • To get a list of all available code snippets, type Ctrl + k, Ctrl + x. This displays the Insert Snippet window in the code editor. This feature can also be accessed by right clicking in the source code editor and selecting the Insert Snippet... menu item.

Section 4.9 Value Types vs. Reference Types

  • Types are divided into two categories—value types and reference types.
  • A variable of a value type contains data of that type.
  • A variable of a reference type (sometimes called a reference) contains the address of a location in memory where an object is stored.
  • Reference-type instance variables are initialized by default to the value null.

Section 4.10 Initializing Objects with Constructors

  • A constructor can be used to initialize an object of a class when the object is created.
  • If no constructor is provided for a class, the compiler provides a public default constructor with no parameters that does not modify the instance variables' default values.
  • Like operations, the UML models constructors in the third compartment of a class diagram. To distinguish a constructor from a class's operations, the UML places the word "constructor" between guillemets (« and µ) before the constructor's name.
  • Constructors can specify parameters but cannot specify return types.

Section 4.11 Floating-Point Numbers and Type decimal

  • A real number is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345. C# provides three simple types for storing real numbers—float, double, and decimal.
  • Types float and double are called floating-point types. The primary difference between them and the decimal type is that decimal variables store a limited range of real numbers precisely, but floating-point variables store approximations of real numbers across a much greater range.
  • Variables of type float represent single-precision floating-point numbers and have seven significant digits. Variables of type double represent double-precision floating-point numbers. These require twice as much storage as float variables and provide 15–16 significant digits—approximately double the precision of float variables. Furthermore, variables of type decimal require twice as much storage as double variables and provide 28–29 significant digits.
  • Real number values that appear in source code are of type double by default.
  • Convert method ToDecimal extracts a decimal value from a string.
  • The : in a format item indicates that the next character represents a format specifier.
  • The C format specifier specifies a monetary amount (C is for currency).
  • It's possible to declare the get and set accessors of a property with different access modifiers. One accessor must implicitly have the same access as the property and the other must be declared with a more restrictive access modifier than the property; private is more restrictive than public.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020