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!


    NEW! Driving Business Success with Rational Process Library

    Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance.
    FREE! Go There Now!


    NEW! Did you say mainframe? e-kit

    Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise.
    FREE! Go There Now!


    NEW! Download IBM Data Studio V1.1

    Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms.
    FREE! Go There Now!


    NEW! Krugle, developerWorks, and code search

    Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Try IBM Rational Asset Manager V7.0 online!

    You can now evaluate IBM Rational Asset Manager V7.0 online without installing or configuring it on your own system! Rational Asset Manager helps create, modify, govern, find, and reuse any type of development assets, including SOA and systems development assets. Rational Asset Manager helps you reduce software development costs and improve quality by facilitating the reuse of all types of software development-related assets. Visit developerWorks to learn more about this product and register to explore its capabilities online.
    FREE! Go There Now!


    NEW! Understanding Web application security challenges

    As businesses grow increasingly dependent upon Web applications, these complex entities grow more difficult to secure. Most companies equip their Web sites with firewalls, Secure Sockets Layer (SSL), and network and host security, but the majority of attacks are on applications themselves – and these technologies cannot prevent them. This paper explains what you can do to help protect your organization, and it discusses an approach for improving your organization’s Web application security.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    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 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek