Search code examples
c#oopconstantsreadonly-attribute

Usage of const in C#


I would like to make the cert variable below to be a const? When I do that, I get an error, "The expression being assigned to cert must be a constant". I have seen articles online asking to convert it to static readonly as opposed to const, and also saying that to be a const, the value should be known at compile time.

I have two questions

  1. Is it not possible for cert to be a const variable, since I do not want it to be modified?
  2. I tried making the cert variable a readonly, and that too gives me an error, "The modifier readonly is not valid for this item".

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IAMAGoodDeveloper
{
    public static class Program
    {
        static void Main(string[] args)
        {
            programStart();
        }

        private static void programStart()
        {
            var myFactory = new MyFactory();
            var secretsProvider = myFactory.GenerateKeyProvider();
            const int cert = secretsProvider.GetKey("arg");
        }
    }
}

MyFactory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IAMAGoodDeveloper
{
    public class MyFactory
    {
        public KeyGen GenerateKeyProvider()
        {
            return new KeyGen();
        }
    }

    public class KeyGen
    {
        public int GetKey(string arg)
        {
            return 1;
        }
    }
}

Solution

  • You cannot use const with instantiated objects. A good alternative would be a static readonly field at class-level though.