How to use constants in .NET?


I have a written this Dev tip for the new folk who entered in this Dev World.

Normally in the development we use some of the success message's or failure messages in general common message's.We do have a habit of writing the messages as given below

MessageBox.Show("Successfully created a record!");

MessageBox.Show("Successfully deleted a record!");

We can make use of Constants in .NET which will be declared using the keyword "const".For the above scenario we can create a  class like "Messages.cs" and define constants as given below


 public class Messages
    {
        public const string strUserExist = "User Name already exists.";
        public const string strUserSaved = "User information saved successfully.";
        public const string strUserDeleted = "User deleted successfully.";
   
    }

Advantage :We can change the message text only in the Message.cs class which will be applicable through out the project where ever we have used this constant.

Usage :

MessageBox.Show(Message.strUserExist);

The above scenario is one of the example I have explained.Guys! There are  many scenario's where we use like this according to the purpose.

We can do this either in Windows or Web Development also.

 I hope this will give a basic idea about constants in .NET to the newbies.

Happy Coding :-)

Popular posts from this blog

Exporting to excel from a custom class object using C#.NET

How to hide bootStrap popover when user click(s) outside the popover?

Get the Clicked Cell Value and Column Name of GridView in ASP.NET