Access Const Property in C#

In our development, we have to treat a Constant Property as a static member, if we need to reference this value. In other words, we have to access the member by using the type name, instead of the object name.

Example

class Book
     {
         public const string Category = "Science";
         public string Name
         {
             get;
             private set;
         }
     public Book(string name){ Name = name;}

The code snippet above is a Book class in a C# project. It has a constant member Category, and its value is Science.

To access Category‘s value, we need to access it by using the type name, instead of the object name. Here is an example and it is valid.

class Program
     {
         static void Main(string[] args)
         {
             var CategoryName = Book.Category;
         }
     }

In the example, we access Category property by using the type name Book, instead of initialising an object.

However, if we access the Category property by using an initialised object, visual studio will throw an error to us. Here is the case.

class Program
     {
         static void Main(string[] args)
         {
             var book = new Book("test");
             var CategoryName = book.Category;
         }
     }

The Visual Studio throws an error to us if we access the Category property by using an object.


8 Replies to “Access Const Property in C#”

  1. I’m extremely pleased to discover this website. I wanted to thank you for ones time just for this fantastic read!! I definitely enjoyed every part of it and i also have you bookmarked to see new stuff in your site.

  2. I’m extremely pleased to discover this website. I wanted to thank you for ones time just for this fantastic read!! I absolutely enjoyed every part of it and i also have you bookmarked to see new stuff in your site.

Leave a Reply

Your email address will not be published. Required fields are marked *