• 0

Using set and get in C Sharp


Question

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?

Link to comment
https://www.neowin.net/forum/topic/721934-using-set-and-get-in-c-sharp/
Share on other sites

13 answers to this question

Recommended Posts

  • 0

The reason the compiler complains is because you are trying to access an instance variable inside a static method. Properties are synctatic sugar for getters and setters, so you should consider them as methods. So, you declare your property as static, but inside the property you try to access m_somenum which is not declared static; that is the problem. You need to either have both the property and its underlying variable static, or none.

If you want "global variables" in C Sharp, you can declare a class containing public static variables, in the global namespace, that is, not in any particular namespace.

  • 0

(Beaten to it, heh)

The problem you're having with your static declarations is that while your accessor/mutator is static, the variable it is accessing is not. In your example, the member m_somenum would need to be static as well. Besides that, I think you have the wrong idea about how they can be used.

What is the point of it? The idea behind these get/set bits of code is to reduce the amount of code needed to achieve information hiding. For example, I'll make a comparison between equivalent code in Java and C#:

/* Java */
class Example
{
  private int _blah;

  public int GetBlah () 
  {
	return _blah;
  }

  public void SetBlah (int newval) 
  {
	/* Maybe do some range checking here */ 
	_blah = newval;
  }
}

/* ...now in some method: */
Example e = new Example();
e.SetBlah(3);
System.out.println("The value is " + e.GetBlah());

/* C# */
class Example
{
  private int _blah;

  public int Blah
  {
	get { return _blah; }
	set 
	{ 
	  /* Maybe do some range checking here */ 
	  _blah = value; 
	}
  }
}

/* Now in some method... */
Example e = new Example();
e.Blah = 3;
Console.WriteLine("The value is " + e.Blah);

If you really don't want to, you don't have to use these accessors/mutators (I think they're referred to as Properties); you could just declare Blah as a public int and be done with it, but that's dangerous.

  • 0
If you really don't want to, you don't have to use these accessors/mutators (I think they're referred to as Properties); you could just declare Blah as a public int and be done with it, but that's dangerous.

Where is the danger? could you explain please? Are you talking about this:

class Example
{
  private int _blah;

  public int Blah
  {
	get { return _blah; }
	set
	{
	  /* Maybe do some range checking here */
	  _blah = value;
	}
  }
}

or this :

public int Test { get; set; }

  • 0
Where is the danger? could you explain please?

Sorry, I should have elaborated.

As MioTheGreat said, the danger lies in giving variables public visibility. It is dangerous because it violates the principle of information hiding, and removes your ability to perform any sensible kind of validation when another peice of code changes the value of the variable. Even if you're not doing any validation and any value would suffice for a particular variable, it'd be a terrible habit to get into, whether it's C# or Java or any other object-oriented language you're programming in.

  • 0
Where is the danger? could you explain please? Are you talking about this:

Previous posters are right about using setters for validation etc. In addition, it may be the case (now or later) that other things depend on the value of that variable. If everyone has direct access then you will never know when its value has been changed.

There's also a strong case for getters, because at some tine in the future you may want to change the internal representation of that data, or virtualise it, or defer initialisation until it's needed, all of which are easy if there's a getter, impossible if the world has direct access to the variable.

Maybe you remember the "year 2k" problem, when companies spent millions changing the internal representation of dates and thus the code of every module that used a date. If those dates had been hidden behind getters the change would have not affected most modules, and thus been an order of magnitude easier.

Edited by JamesCherrill
  • 0
public int Test { get; set; }

Used this way, this is an example of C#'s automatic getters and setters. Realistically you are not doing anything different, its just that the compiler generates the field responsible for this property:

public int Test { get; set; }

Will translate to:

[CompilerGenerated]
private int <Test>k__BackingField;

public int Test
{
	[CompilerGenerated]
	get
	{
		return this.<Test>k__BackingField;
	}
	[CompilerGenerated]
	set
	{
		this.<Test>k__BackingField = value;
	}
}

Well, in IL equivalent.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I bought one of these last year. I really hope I won't have to deal with this crap. My drive is in good condition at the moment.
    • Umm, read my answer again! If you have something to add or contribute, feel free. Otherwise my point was that you apparently dont want faster updates... so you want slower updates by process of elimination. If you have something to contribute, meaningful answers are better.
    • These features described above are good, but far from what developers will like the most. The main feature that developers will care and love the most it's called "Bring Your Own Models". It gives us the ability to connect to LOCAL AI models running on Ollama. The feature it's located on GitHub Copilot tab -> On the model picker where you can select "manage models" instead of paid models and then it will show you the "Bring your own models" window where you can now select Ollama and the endpoint of your local server. So if you have a beefy spec machine you can now use your own model 100% local inside Visual Studio 2026 18.7.0
    • Microsoft Teams is getting a controversial location tracking feature that users may hate by Usama Jawad Image generated with Microsoft Copilot Earlier this year, Microsoft planned to roll out a controversial location tracking feature in Teams, but following customer feedback, it decided to delay its release. The bad news is that the company has decided to launch it later this year, but it's based on roughly the same design that was shared earlier, which means that many users still have good reason to worry. Basically, Microsoft Places and Teams have received workplace check-ins via Wi-Fi. The idea is that if an employee arrives at the office and connects to their enterprise network, their profile status indicator will show them as being present in the office. For example, if you arrive at work, open Teams on your PC, and connect to the "Studio B" company Wi-Fi network, your Teams profile will indicate that you are present in "Studio B", as shown below: Microsoft says that this feature is basically a replacement for physical workplace check-in peripherals, it reduces the need to manually update your status, and it also enables co-workers to know that you're at work so that they can coordinate in-person meetings with you. IT admins can enable this workplace check-in capability at a tenant level, and users have the ability to control whether they want to enable it or not. Of course, all of that sounds great on paper, but naturally, many Teams customers may still have concerns, as they did before. This is because it enables your reporting manager and other members of the organization to track if you are at the office, when you arrive at the office, and where you are right now. This could be problematic for people who work in what they consider to be flexible work environments or hybrid setups, and this kind of location tracking could be considered an invasion of privacy. Microsoft has tried to alleviate some of these concerns by letting users know that they can manually set their location easily, which essentially overrides workplace check-in if they feel uncomfortable with it. However, that doesn't really solve the problem because your organization could enforce a workplace policy that mandates that this feature remains enabled. The Redmond tech giant has also assured users that this capability does not store historical data and is only a real-time indicator of location. Finally, it only generates a signal when you connect to a corporate network, which means that if you are working from home and connect your PC to your personal Wi-Fi, it won't broadcast your location to your employer; you will simply be shown as "Remote". Microsoft has encouraged IT admins to prepare for this change and begin informing users so they know what to expect once it begins rolling out later this year.
  • Recent Achievements

    • Very Popular
      AndrewSteel earned a badge
      Very Popular
    • Veteran
      Taliseian went up a rank
      Veteran
    • One Month Later
      Clizby earned a badge
      One Month Later
    • One Month Later
      Timaximus earned a badge
      One Month Later
    • Week One Done
      Timaximus earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      516
    2. 2
      +Edouard
      162
    3. 3
      PsYcHoKiLLa
      157
    4. 4
      Steven P.
      82
    5. 5
      ATLien_0
      81
  • Tell a friend

    Love Neowin? Tell a friend!