public static void DoSomething()
{
int a;
string b;
//..do something
}
In the example above, i have declared two variables. Do they become static because the method that contains them is static?
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
Static variables offer some of the benefit of global variables (they don't get destroyed until the end of the program) while limiting their visibility to block scope. This makes them safer for use even if you change their values regularly.
Local variables in static methods are just local variables in a static method. They're not static, and they're not special in any way. Static variables are held in memory attached to the corresponding Class objects; any objects referenced by static reference variables just live in the regular heap.
No. Only the method is static but not variables.
From MSDN:
C# does not support static local variables (variables that are declared in method scope).
if you want to have static variable in static member, do the declaration outside the static method,
private static int _var = 0;
public static void SampleMethod()
{
_var++;
}
Although available in C, static local variables are not supported in C#.
If you want a local static variable equivalent, you can create an instance variable on the class, or a static variable. Otherwise, consider if the method itself belongs to the static class and whether it should be part of a different type.
From MSDN
C# does not support static local variables (variables that are declared in method scope).
I am positive with your opinion but in the sample code below i'am taking an access violation exception about using protected memory. Because of that maybe it isn't support static local variables but in memory management it can point same address.
public static byte[] RawSerialize(object anything)
{
int rawsize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawdata = new byte[rawsize];
Marshal.Copy(buffer, rawdata, 0, rawsize);
Marshal.FreeHGlobal(buffer);
return rawdata ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With