Privately set able and publicly get able property in C#


Properties in C# classes are safer way to access and manipulate data. With Set and Get function user can configure the functionality. How about a privately Get able property, which can be accessible only through the class itself and publicly setable property.

This can be done by putting private keyword before the set property.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Data
    {
        private String Narration;

        public Data()
        {
            this.Narration = “Expese”;
         
        }
        public string narration
        {
         
            get
            {
                return  Narration;
            }
            private set
            {
                Narration=value;
            }
        }
        public void SetData()
        {
            this.narration = “Other expense”;
        }

    }
}

Let’s configure the console application. Create the object call the properties and methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Data d = new Data();
            Console.WriteLine(d.narration);
         
            d.SetData();
            Console.WriteLine(d.narration);
 Console.ReadKey();
        }
    }
}

The SetData() is call the privately get able property, which can be on;y accessible within the class itself.

The public property can access the data because it is public property and by default all set and get are public.

Download Source

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.