How do I create properties in C#?

Category: Introduction, viewed: 1164 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
{
    public 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;
            }
        }

        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);
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page