Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing of constant variable using method (C#)

Tags:

c#

c#-4.0

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.

like image 876
user1461511 Avatar asked Jun 17 '13 06:06

user1461511


2 Answers

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.

like image 177
Darin Dimitrov Avatar answered Sep 20 '22 22:09

Darin Dimitrov


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();
like image 42
Vishal Suthar Avatar answered Sep 24 '22 22:09

Vishal Suthar