Reputation: 661
I'm trying to wrap my head around Ruby variables and thought it might be good to see them in terms of C#
could someone tell me the C# equivalent of Ruby's (for example is @@ == public static variable?):
$ global variable
@ instance variable
@@ class variable
[a-z] local variable
[A-Z] constant
any other types of variables I'm missing?
Could someone also explain how @instance variables are used/function?
at first I thought it was some global variable in the instance of a class, but then i saw it used with a scope like a local variable in the instance's method.
here's is an example from the 'well grounded rubyist'
class C
def show_var
@v = "i am an instance variable initialized to a string"
puts @v
end
@v = "instance variables can appear anywhere..."
end
C.new.show_var
if I wanted 'v' to be the same variable from anywhere in the class instance, what is the Ruby mechanism for doing this?
Upvotes: 0
Views: 549
Reputation: 7719
C# does not use sigils for variables.
The "equivalent" C# variable depends entirely on how the variable/member is defined. Note that there are differences even between the "equivalent" forms.
However, there are a number of naming conventions that are encouraged to be followed. The exact conventions used vary by project and may differ from the names I chose below, which reflect my conventions - do not use "class" or "instance" or "local" in real variable names.
Examples:
class MyClass: IMyInterface {
// "const" makes it constant, not the name
public const int CONSTANT = 42;
// static member variable - somewhat like Ruby's @@variable
private static int classVariable;
public static int ExposedClassVariable; // but use properties
// @variable - unlike Ruby, can be accessed outside "self" scope
int instanceVariable;
public int ExposedInstanceVariable; // but use properties
void method (int parameter) {
int localVariable;
}
}
C# does not have "global variables in a shared namespace", but static member variables can be accessed by a stable path which means they can be effectively abused as global variables.
Upvotes: 2