PDA

View Full Version : Using set and get in C Sharp


complete
01-13-2009, 10:44 PM
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?

oracleguy
01-14-2009, 12:26 AM
The set and get are designed to be properties of an object, it is an cleaner way to write properties in a class versus using setter and getter methods in a class as you would do in C++.

So this would be an example:

class PropertyExample
{

private int m_number = 0;

public int number
{
get
{
return m_number;
}
set
{
m_number = value;
}
}

}


This is much more preferable than just making m_number public because then you can control access to the variable better and validate input if need be. Also you can specify only the set or only the get which can make a property read only or write only.

Data members in a class regardless of being static or not do not need the set and get functions, their access is controlled by the access specifier (e.g. public, protected, internal, private).

In C# everything is an object which means unless a data member or method in a class is static, the class has to be instantiated before you can use it.

To have a class with a publicly accessible static data member it would be something like:

class SomeClass
{
public static int MyVariable;
}


But really the question you should ask yourself is why you need to do this. This essentially creates a global variable, which is a bad idea. Global variables should only be used as a very last resort, typically you don't actually need to use one.