How do you introduce a ReadOnly property in C#?

If you want to define a property whose value can only be read but not set, then you can do it using ReadOnly property in C#. ReadOnly is achieved by defining only the get accessor method for the property. The property will not have a set accessor method.



Here is an example:
public class sampleClass {
private string member1;
public sampleClass(string member1) {
this.member1 = member1;
}
public string Member1 {
get { return member1; }
}
public static void Main() {
sampleClass obj = new sampleClass(“sample message”);
Console.WriteLine(“obj.Member1 = “ + obj.Member1);
}
}

Output of this code will be:

Obj.Member1 = sample message

In this example, the property Member1 is readonly since it has only the get accessor method. If the Main method includes the following line of code:

obj.Member1 = “test message”;

Then you will get the following error since the property Member1 is readonly:

Property or indexer ‘sampleClass.Member1' cannot be assigned to -- it is read only

| Can you call a constructor from another constructor of the Class in .NET? | Difference between Response.Output.Write() method and Response.Write() method in .NET | How do you establish multiple inheritance in C#? | How do you introduce a ReadOnly property in C#? | How do you perform constructor overloading in C#? | Is catch(Exception) recommended to be used in .NET? | What are the different access modifiers available in C#? | What are the different ways of overloading in C#? | What are the members of stringbuilder class in C#? | What is Multicast Delegate? Explain it with example in C# | What is the difference between abstract class and interface in .NET? | What is the difference between Clone and CopyTo methods in .NET | What is the difference between const and readonly in .NET | What is the difference between directcast and ctype in .NET? | What is the difference between out and ref parameters in .NET | What is the difference between public assembly and private assembly in .NET | What is the difference between strong typing and weak typing in .NET? | What is the difference between Trace and Debug in .NET | What is the need for Abstract Factory Pattern in C#? | What is the need for Adapter Pattern in C# |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.