Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting conditional statements inside static class in C#

Tags:

c#

I have a below class:

public static class AllAcess
{
    public static int var1;

    //Some conditional statements
    if(somecondition)
    {
        var1 = x;
    }
    else
    {
        var1 = y;
    }
}

How can i put some conditional statement inside class. Currently it's not allowing if ,else etc .

Please suggest logic which can be used as condition here.

I want to access var1 from other classes.

like image 860
AllTech Avatar asked Feb 28 '26 08:02

AllTech


1 Answers

You probably want a static constructor:

public static class AllAcess
{
    public static int var1;

    static AllAcess()
    {
        if (somecondition)
        {
            var1 = x;
        }
        else
        {
            var1 = y;
        }
    }
}

This is run at some point before var1 is accessed for the first time.

Note, do not do anything too complicated in a static constructor. Do not do anything which touches the filesystem or network, or does any threading.

like image 131
canton7 Avatar answered Mar 01 '26 20:03

canton7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!