const vs. readonly in C#

In c# what the hell is the difference between const and readonly?  I looked this up today and:

Here’s what I found.

Constants (const):

  • Are slightly less expensive to evealuate
  • Are static by default
  • Can be declared inside functions
  • Have gotta have compile time value
  • Are set at compile time inside assemblies that use them

Readonly (readonly) instance fields:

  • Must have set value by the time constructor exits
  • Are evaluated when instance is created

So I tend to use readonly fields if I ever think the constant will be referenced outside of my assembly.  Otherwise I’ll take the microsecond and use a const.

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 )

Facebook photo

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

Connecting to %s