5

Is it possible to initializing value of a constant value using method of another class

namespace ConsoleApplication1
{
    class Program
    {
        const int gravit = haha.habc();//something like this
        static void Main(string[] args)
        {
            some codes.....

        }
        public class haha
        {
            int gar = 1;
            public int habc()
            {
                int sa = 1;
                return sa;
            }

        }
    }
}

For example like the codes above(FYI with this code I am getting Expression being assigned to ... must be constant), if not is there other method to do something similar to this.

1
  • 4
    "constant variable" pretty much sums up the misunderstanding here ;-) Commented Jun 17, 2013 at 6:30

2 Answers 2

7

No, that's not possible, you could use readonly field instead because constant values should be known at compile-time:

private static readonly int gravit = haha.habc();//something like this

NOTE: the habc method should be static if you want to call it that way.

Sign up to request clarification or add additional context in comments.

2 Comments

@DarinDimitrov - Is Dependency Resolver missing in the code line private static readonly int gravit = haha.habc(); ?
value returned by this function int A() => 1; is known even before compile time.
1

Constants are values which should be known at compile time and do not change. So the ReadOnly is the option you should go with.

private readonly int gravit = haha.habc();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.