How do I create properties in C#?

Category: Introduction, viewed: 4K time(s).

In this example we create a property. Property is used to read or write fields or attributes of a class. In our User class web have four fields id, username, firstName, lastName. Next we create properties for setting and getting the value of the property.

using System;

namespace Kodecsharp.Example.Intro
{
    class PropertyDemo
    {
        [STAThread]
        public static void Main(string[] args)
        {
            User user = new User();
            user.Id = 1;
            user.Username = "admin";
            user.FirstName = "System";
            user.LastName = "Administrator";

            System.Console.WriteLine("User: " + user.Id + "; " +
                user.Username + "; " + user.FirstName + "; " +
                user.LastName);
        }
    }

    class User
    {
        private long id;
        private string username;
        private string firstName;
        private string lastName;

        public User()
        {
        }

        /// <summary>
        /// User ID Property
        /// </summary>
        public long Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        /// <summary>
        /// Username Property
        /// </summary>
        public string Username
        {
            get
            {
                return username;
            }
            set
            {
                username = value;
            }
        }

        /// <summary>
        /// Firstname Property
        /// </summary>
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName = value;
            }
        }

        /// <summary>
        /// Lastname Property
        /// </summary>
        public string LastName
        {
            get
            {
                return lastName;
            }
            set
            {
                lastName = value;
            }
        }        
    }
}

Since C# 3, there is a new way to implement properties in a class. This feature called the auto-implemented properties. You can see the following example about auto-implemented properties: How do I create an auto implemented properties?

Powered by Disqus