Skip to main content
Read-only auto-properties in csharp 6.0 with example

Read-only auto-properties in csharp 6.0 with example

You might already be aware that Microsoft had launched a version of CSharp called C# 6.0 with Visual Studio Ultimate 2015 Preview and there is a feature in C# 6.0 called “Read-only auto-properties“.

Read-only auto-properties in csharp 6.0 #csharp #microsoft #developers Click To Tweet

This feature allows us to create a read-only property with just a get, no set.

Let’s look at this with the help of an example.

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

namespace Read_only_auto_properties_csharp_6
{
    class Program
    {
        static void Main(string[] args)
        {

        }
    }

    public class MyClass
    {
        public int MyProp { get; }
    }
}

With the above code, we will get a successful build.

However, while executing the same code in Visual Studio 2012 that works with C# 5.0, it gives an unsuccessful build due to an error.

Read-only auto-properties in csharp 6.0

In C# 6.0, writing a property only with “get“, it automatically becomes a Read Only property.

For more explanation, let’s take another example with some code where we:

  • Declare a property with only a “get
  • Assign a value to it
  • Access it with the object of that class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Read_only_auto_properties_csharp_6
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            Console.WriteLine(obj.MyProp);
            Console.ReadKey();
        }

    }

    public class MyClass
    {
        public int MyProp { get; }

        public MyClass()
        {
            MyProp = 10;
        }

    }
}

Nevertheless, when we set a value of that property again, it gives the error and says it is a read only property.

Read-only auto-properties in csharp 6.0

To know more about C# features with respect to its versions, navigate to the below post.

List of C# features version by version

What do you think?

Dear Readers,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Programming!

Was this article worth reading? Share it with fellow developers too.

DotNetCrunch

DotNetCrunch is a popular blog for latest Microsoft® technologies which is aimed for beginners and intermediate level professionals.