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! Improve your build process with IBM Rational Build Forge, Part 2: Automate builds for a real-world Tomcat project

    Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available.
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    FREE! Go There Now!


    NEW! Best Practices: The Integrated Project and Portfolio Management Platform.

    Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan.
    FREE! Go There Now!


    NEW! Addressing software-as-a-service challenges using Tivoli security and WebSphere solutions

    Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base.
    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! Rational Testing eKits

    Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing.
    FREE! Go There Now!


    Role of Integrated Requirements Management in Software Delivery

    As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change.
    FREE! Go There Now!


    NEW! Rational Asset Manager eKit

    Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions.
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP applications.
    FREE! Go There Now!


    NEW! Achieving True Agility -- How process can change the behavior of your tools

    Achieving true agility is a never-ending effort. We will showcase how you can become agile incrementally, a few practices at the time.Which practices should any agile team strive to adopt? What additional practices should you consider based on your needs to scale? Adopting practices are however made much easier with the right tool support. What about if your tools adapt to your practices? We will take a look at how the Jazz technology can be leveraged to make your process change the behavior of your tools.
    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 4 Hosted by Hostway
    Stay green...Green IT