C#
  Home arrow C# arrow Understanding Properties in C#
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Understanding Properties in C#
By: Rajesh V S
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 39
    2003-04-28

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    This article is designed to further your knowledge about properties in the C# language. Read how Rajesh uses get and set methods to access these properties.

    In C#, properties are nothing but natural extension of data fields. They are usually known as ‘smart fields’ in C# community. We know that data encapsulation and hiding are the two fundamental characteristics of any object oriented programming language. In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members. 

    Usually inside a class, we declare a data field as private and will provide a set of public SET and GET methods to access the data fields. This is a good programming practice, since the data fields are not directly accessible out side the class. We must use the set/get methods to access the data fields. 

    An example, which uses a set of set/get methods, is shown below. 

    //SET/GET methods
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClass
    {
                private int x;
                public void SetX(int i)
                {
                            x = i;
                }
                public int GetX()
                {
                            return x;
                }
    }
    class MyClient
    {
                public static void Main()
                {
                            MyClass mc = new MyClass();
                            mc.SetX(10);
                            int xVal = mc.GetX();
                            Console.WriteLine(xVal);//Displays 10
                }

    But C# provides a built in mechanism called properties to do the above. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.

    <acces_modifier> <return_type> <property_name>
    {
               get
               {
               }
               set
               {
               }
    }

    Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor. 

    For example the above program can be modifies with a property X as follows. 

    class MyClass
    {
               private int x;
               public int X
               {
                          get
                          {
                                      return x;
                          }
                          set
                          {
                                      x = value;
                          }
               }
    }
     

    The object of the class MyClass can access the property X as follows.

    MyClass mc = new MyClass();
    mc.X = 10; // calls set accessor of the property X, and pass 10 as value of the standard field
    //‘value’. This is used for setting value for the data member x.
    Console.WriteLine(mc.X);// displays 10. Calls the get accessor of the property X.
     

    The complete program is shown below. 

    //C#: Property
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClass
    {
                private int x;
                public int X
                {
                            get
                            {
                                        return x;
                            }
                            set
                            {
                                        x = value;
                            }
                }
    }
    class MyClient
    {
                public static void Main()
                {
                            MyClass mc = new MyClass();
                            mc.X = 10;
                            int xVal = mc.X;
                            Console.WriteLine(xVal);//Displays 10
                }
    }
     

    Remember that a property should have at least one accessor, either set or get. The set accessor has a free variable available in it called value, which gets created automatically by the compiler. We can’t declare any variable with the name value inside the set accessor.

    We can do very complicated calculations inside the set or get accessor. Even they can throw exceptions. 

    Since normal data fields and properties are stored in the same memory space, in C#, it is not possible to declare a field and property with the same name. 

    Static Properties

    C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. 

    The following program shows a class with a static property. 

    //C# : static Property
    //Author:
    rajeshvs@msn.com
    using System;
    class MyClass
    {
                private  static int x;
                public static int X
                {
                            get
                            {
                                        return x;
                            }
                            set
                            {
                                        x = value;
                            }
                }
    }
    class MyClient
    {
                public static void Main()
                {
                            MyClass.X = 10;
                            int xVal = MyClass.X;
                                    Console.WriteLine(xVal);//Displays 10
                }
    }
     

    Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name. 

    Properties & Inheritance 

    The properties of a Base class can be inherited to a Derived class. 

    //C# : Property : Inheritance
    //Author:
    rajeshvs@msn.com
    using System;
    class Base
    {
                public int X
                {
                            get
                            {
                                        Console.Write("Base GET");
                                        return 10;
                            }
                            set
                            {
                                        Console.Write("Base SET");
                            }
                }
    }
    class Derived : Base
    {
               
    }
    class MyClient
    {
                public static void Main()
                {
                            Derived d1 = new Derived();
                            d1.X = 10;
                            Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
                }
    }
     

    The above program is very straightforward. The inheritance of properties is just like inheritance any other member. 

    Properties & Polymorphism 

    A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level. 

    //C# : Property : Polymorphism
    //Author:
    rajeshvs@msn.com
    using System;
    class Base
    {
                public virtual int X
                    {
                                    get
                            {
                                        Console.Write("Base GET");
                                        return 10;
                            }
                            set
                            {
                                        Console.Write("Base SET");
                            }
                }
    }
    class Derived : Base
    {
                public override int X
                {
                            get
                            {
                                        Console.Write("Derived GET");
                                        return 10;
                            }
                            set
                            {
                                        Console.Write("Derived SET");
                            }
                }         
    }
    class MyClient
    {
                public static void Main()
                {
                            Base b1 = new Derived();
                            b1.X = 10;
                            Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
                }
    }

    Abstract Properties 

    A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. 

    If the abstract class contains only set accessor, we can implement only set in the derived class. 

    The following program shows an abstract property in action. 

    //C# : Property : Abstract
    //Author:
    rajeshvs@msn.com
    using System;
    abstract class Abstract
    {
                public abstract int X
                {
                            get;
                            set;
                }
    }
    class Concrete : Abstract
    {
                public override int X
                {
                            get
                            {
                                        Console.Write(" GET");
                                        return 10;
                            }
                            set
                            {
                                        Console.Write(" SET");
                            }
                }         
    }
    class MyClient
    {
                public static void Main()
                {
                            Concrete c1 = new Concrete();
                            c1.X = 10;
                            Console.WriteLine(c1.X);//Displays 'SET GET 10'
                }
    }

    The properties are an important features added in language level inside C#. They are very useful in GUI programming. Remember that the compiler actually generates the appropriate getter and setter methods when it parses the C# property syntax.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More C# Articles
    More By Rajesh V S

     

    IBM® developerWorks developerWorks - FREE Tools!


    IBM DB2 Deep Compression ROI Tool

    The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times.
    FREE! Go There Now!


    NEW! Best Practices in Integrated Requirements Management

    Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right."
    FREE! Go There Now!


    NEW! Download DB2 Express-C 9.5

    Visit IBM developerWorks to download IBM DB2 Express-C 9.5, a no-charge version of DB2 Express 9 database server. DB2 Express-C offers the same core data server base features as other DB2 Express editions and provides a solid base to build and deploy applications developed using C/C++, Java, .NET, PHP, and other programming languages.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! IBM Rational AppScan Standard Edition V7.7

    Secure your Web applications with IBM Rational AppScan Standard Edition V7.7, previously known as Watchfire AppScan. This Web application security testing tool automates vulnerability assessments and scans and tests for common Web application vulnerabilities. Visit IBM developerWorks to download a free trial of IBM Rational AppScan Standard Edition V7.7.
    FREE! Go There Now!


    NEW! Run your first CICS application on a PC using TXSeries for Windows

    Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1.
    FREE! Go There Now!


    NEW! The dirty dozen: preventing common application-level hack attacks

    As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications.
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!


    NEW! Webcast: Calling All Testers! Find Application Vulnerabilities Early in the Development Process Where they are Easier to Fix and Less Risky to your Business

    In this webcast, IBM Rational will discuss the importance of Web application security and will share techniques and best practices to introduce application security testing into current QA processes including: understanding common security vulnerabilities and techniques to integrate security testing with defect tracking and remediation systems in an effort to safeguard sensitive online information.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    C# ARTICLES

    - Introduction to Objects and Classes in C#, P...
    - Visual C#.NET, Part 1: Introduction to Progr...
    - C# - An Introduction
    - Hotmail Exposed: Access Hotmail using C#
    - Razor Sharp C#
    - Introduction to Objects and Classes in C#
    - Making Your Code CLS Compliant
    - Programming with MySQL and .NET Technologies
    - Socket Programming in C# - Part II
    - Socket Programming in C# - Part I
    - Creational Patterns in C#
    - Type Conversions
    - Creating Custom Delegates and Events in C#
    - Inheritance and Polymorphism
    - Understanding Properties in C#







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT