PositiveGuy
PositiveGuy

Reputation: 47743

Can't create static variable inside a static method?

Why won't this work?

public static int[] GetListOfAllDaysForMonths()
{
    static int[] MonthDays = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};

    return MonthDays;
}

I had to move the variable declaration outside of the method:

    static int[] MonthDays = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
public static int[] GetListOfAllDaysForMonths()
{
    return MonthDays;
}

Also, so by creating it this way, we only have one instance of this array floating around in memory? This method sits inside a static class.

Upvotes: 1

Views: 1330

Answers (4)

Joel Coehoorn
Joel Coehoorn

Reputation: 415800

C# doesn't support static locals at all. Anything static needs to be a member of a type or a type itself (ie, static class).

Btw, VB.Net does have support for static locals, but it's accomplished by re-writing your code at compile time to move the variable to the type level (and lock the initial assignment with the Monitor class for basic thread safety).

[post-accept addendum]
Personally, your code sample looks meaningless to me unless you tie it to a real month. I'd do something like this:

public static IEnumerable<DateTime> GetDaysInMonth(DateTime d)
{
    d = new DateTime(d.Year, d.Month, 1);
    return Enumerable.Range(0, DateTime.DaysInMonth(d.Year, d.Month))
             .Select(i => d.AddDays(i) );
}

Note also that I'm not using an array. Arrays should be avoided in .Net, unless you really know why you're using an array instead of something else.

Upvotes: 17

Wim
Wim

Reputation: 12082

Well, apart from it not being supported, why would you want to? If you need to define something inside a method, it has local scope, and clearly doesn't need anything more than that.

Upvotes: 0

ElGringoGrande
ElGringoGrande

Reputation: 638

What would be the scope of that static variable declared within the method? I don't think CLR supports method static variables, does it?

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

You can only create static variables in the class/struct scope. They are static, meaning they are defined on the type (not the method).

This is how C# uses the term "static", which is different from how "static" is used in some other languages.

Upvotes: 8

Related Questions