C# Constants (valuable features to know)

January 17, 2011

Constants: Not as easy as u might have thought about it!!!

The Constants as you might have read, ‘a value that can never be changed.’ now it does not end with here. There is something more you need to know about constants in C#.

as we define a constant value,

public const int i=10;

Now here i is an integer value of access public and the use of ‘const’ makes it a constant, i.e a static value through out such that when ever used by any other class and members its value stays unchanged.

You must remember:

  • you can not use constants for your parameters and also in the return value of your methods.
  • a constant is assigned a value during the compile time, and so we can not use a constant to refer to an object as the objects are to deal with the runtime whereas the constants as we know are dealing with the compile time.

Sample Code:

namespace ns_constants

{

public class constsample

{

public const int ciVal1 = 10;

public const int csStrng = “hello friends!”;
public static void Main (string[] args)

{

const string csStrng2 = “you can not change me!!”;

Console.WriteLine(“ciVal1 = {0}”, ciVal1);

Console.WriteLine(“csStrng = {0}”, csStrng);

Console.WriteLine(“csStrng2 = {0}”, csStrng2);

}

}

}

This is it. Let me know your comments and feed backs.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: