What is the point of using set and get in C Sharp?
It seems variables are used differently in this language than in C++.
For some reason, you have to have a static variable defined like this:
public static uint Somenum
{
set { m_somenum = value; }
get { return m_somenum; }
}
and prior to this declaration, you need to have this:
public uint m_sumenum;
This seems to be the only way to expose a member of a class to other classes in C#.
The problem is that I seem to be doing this improperly because I get a compile error:
An object reference is required for the non-static field, metod, or property '.......m_somenum"
I think I see the problem. The problem is that I cannot use a static varable like this.
So you have to instantiate the class in order to set these members of the class.
So how would you do the equivalent of a global class in C Sharp?
Would I do it something like this:
public clase SomeClass
{
SomeClass someclass = new SomeClass();
public static uint Somenum
{
set { m_somenum = value; }
get { return m_somenum; }
}
}
Or perhaps this "new" needs to be outside of the class in order to work. So my next question is this. How and where would that command be such that it the internal set methods could be accessed by the other classes in the code?

Alister MortonPosted Jan 14, 2009, 4:43 AM
e.g
class Class1
{
static int s_value; // shared by all instances
int i_value; // Per instance
public static int StaticVal
{
get
{
return s_value;
}
set
{
s_value = value;
}
}
public int IValue
{
get
{
return i_value;
}
set
{
i_value = value;
}
}
}
Then you would write code such as
Class1.StaticVal = 5;
Class1 c = new Class1();
c.IValue = 4;
Why use get/set rather than making the variables public? Well one reason is that by using get and set methods you can impose conditions on the range of values that can be imposed on your variables, for example you could restrict the static value to only take values from -10 to 10 by changing the accessors to
public static int StaticVal
{
get
{
return s_value;
}
set
{
if (value >= -10 && value <= 10)
{
s_value = value;
}
}
}
Normally of course you'd use a meaningful named constant rather than just dumping a number in the code.
Guest UserPosted Jan 13, 2009, 5:09 PM