Why can't I use some modifier in method? C#

Shervan360 1,541 Reputation points
2024-09-28T01:25:02.2433333+00:00

Hello,

Why can't I use const for a string array and read-only for an integer inside a method?

namespace ConsoleApp1
{
     internal class Program
     {
          static void Main(string[] args)
          {
          }
          static void Summary()
          {
               readonly int a = 10; //Wrong!
               readonly String sr = "10"; //Wrong
               const string s = "10"; //OK
               const string[] summaries = //Wrong!
                {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
                };
               readonly string[] summaries = //Wrong!
             {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
                };
          }
     }
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,833 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,899 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Marcin Policht 23,545 Reputation points MVP
    2024-09-28T01:30:38.82+00:00

    In C#, there are distinct rules for how const and readonly are applied, which explains why you encountered issues using them as you did in the code.

    1. const:
    • Constant values (const) must be assigned a value that can be fully determined at compile-time. Therefore, you can only use const for primitive types like int, string, or other simple types where the value is known at compile-time.
    • For example
    const string s = "10"; // This is OK because the value "10" is known at compile time.
    

    However, arrays or objects cannot be declared as const, because the runtime memory for objects or arrays is allocated dynamically, and the array values are not known at compile-time.

    const string[] summaries = { "Freezing", "Bracing", "Chilly" }; // Wrong!
    
    1. readonly:
    • Readonly fields can only be assigned a value once during initialization (in the constructor or at declaration). The value can be set at runtime, unlike const, but it cannot be changed after being set.
    • The keyword readonly can only be used for class-level fields, meaning you cannot declare local variables inside a method as readonly.
    readonly int a = 10; // Wrong! 'readonly' cannot be used in methods.
    

    What's allowed:

    • You can use const for compile-time constants of simple types (e.g., int, string).
    • You can use readonly for instance fields but not for local variables inside a method.

    Corrected version:

    namespace ConsoleApp1
    {
        internal class Program
        {
            // Correct use of 'readonly' as a field (not inside a method)
            private static readonly string[] summaries = 
            {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };
            // Correct use of 'const' for compile-time constants
            private const string s = "10";
            static void Main(string[] args)
            {
            }
            static void Summary()
            {
                // You can declare 'const' inside the method
                const string methodString = "Sample string"; // OK
                // 'readonly' cannot be used for local variables inside a method.
            }
        }
    }
    

    Key Differences:

    • const applies to compile-time constants (simple types like int or string).
    • readonly applies to class-level fields that can be assigned a value at runtime but remain immutable once set.

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.