• Advertisement
Sign in to follow this  

c# - static function members - huh ?

This topic is 4932 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Well, I'm concidering c# :) While I was testing some stuff I noticed that I can't declare static data inside a function?? Then how is that done in C# then ? int CalculateOnce() { static int the_result = Calculate(); return the_result } Seems odd to me ?

Share this post


Link to post
Share on other sites
Advertisement
This is not possible in C# or .NET in general, though some languages use a workaround. The reason is that in .NET functions do not have "state", only types do.

In C#, if you want to do this, use a private member variable (static). VB.NET and MC++ attain this behavior in the same way, just behind the scenes. The use of static creates a "hidden" private static member in the class.

Matt

Share this post


Link to post
Share on other sites

namespace GameDev.Samples
{
public class Calculate
{
static private int the_result = 0;

static Calculate()
{
the_result = Calculate.Now();
}

public static int Once()
{
return the_result;
}

private static Now()
{
// Do calculation here.
}
}
}




Static constructor will assign the variable for you. Calculate.Once() will return the result. You could create an accessor to do the same thing though:


static public int Once
{
get
{
return this.the_result;
}
}




Make any supporting functions static as well unless you want to instantiate an object behind the scenes.

An explanation as to why C# doesn't support C# function level static variables can be found at http://blogs.msdn.com/csharpfaq/archive/2004/05/11/130248.aspx. Primarily thread issues.

(This is exactly what CpMan said. I'm just providing a code example to his explanation.)

Share this post


Link to post
Share on other sites
Quote:
Original post by Talonius
*** Source Snippet Removed ***

Static constructor will assign the variable for you. Calculate.Once() will return the result. You could create an accessor to do the same thing though:

*** Source Snippet Removed ***

Make any supporting functions static as well unless you want to instantiate an object behind the scenes.

An explanation as to why C# doesn't support C# function level static variables can be found at http://blogs.msdn.com/csharpfaq/archive/2004/05/11/130248.aspx. Primarily thread issues.

(This is exactly what CpMan said. I'm just providing a code example to his explanation.)


Thanks for the help.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement