Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a static variable shared across all instance?

Tags:

c#

.net

c#-4.0

In a public class, I have a private static Dictionary. Since the Dictionary is static, does it mean that it is shared across all the other instance of the same object (see example below).

public class Tax
{
    private static Dictionary<string, double> TaxBrakets = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase)
    {
        { "Individual",   0.18 },
        { "Business",     0.20 },
        { "Other",        0.22 },
    };

    public string Type { get; set; }
    public double ComputeTax(string type, double d)
    {
        return d * TaxBrakets[this.Type];
    }
}

Is that acceptable to use a Dictionary in that way (as static variable)?

like image 254
Martin Avatar asked May 10 '11 21:05

Martin


2 Answers

Your static variable TaxBrakets is not associated with an instance. this.TaxBrakets would not compile. All occurrences of TaxBrakets will refer to the same dictionary. In general, it's totally acceptable to use static dictionaries. This particular use seems a little funny though, but I'd need to see more code to suggest any changes.

like image 106
recursive Avatar answered Sep 19 '22 09:09

recursive


Yes, a static variable exists only once in your entire program, I think it will behave the way you expect.

Whether that's the right solution to your accounting problem is debatable, IANAA but my understanding is that tax brackets (note: the correct spelling of "brackets" has a c) equate income levels to marginal tax rates, knowing the type of the entity is not by itself sufficient to determine the tax rate.

like image 41
Ben Voigt Avatar answered Sep 21 '22 09:09

Ben Voigt