• 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

    • When will the Photos app be updated to remember the window size and position when reopened? They addressed this issue in a 2024 version of the app (though I can't recall the build number). Unfortunately, after that specific version, the problem persists! Please prioritise this fix in your K2 schedule. Additionally, the Snipping Tool has lost the ability to capture the Windows Taskbar starting from the 2024 version!
    • Same, never saw it on Android or iOS. Guess only some people got it *shrugs*
    • Anthropic pulls Fable 5 and Mythos 5 after US export control order by Pradeep Viswanathan In April this year, Anthropic launched the Claude Mythos Preview frontier model with state-of-the-art cyber and coding capabilities for a select set of companies around the world. After preparing appropriate guardrails, early this week, Anthropic launched Claude Fable 5 and Mythos 5, its most capable AI models. Claude Fable 5 is for general users and comes with strict safeguards, while Mythos 5 is designed with fewer safeguards for cybersecurity and biology use cases. Today, Anthropic abruptly suspended access to its Fable 5 and Mythos 5 AI models for all customers after receiving an export control directive from the US government. The company received the directive from the government today at 5:21 p.m. ET, and the received letter did not provide any details regarding the national security concern. Anthropic understands that the government became aware of a method to bypass, or “jailbreak,” Fable 5, which might be the reason behind the directive. The order was issued under national security authorities and requires the company to suspend all access to Fable 5 and Mythos 5 by any foreign national, whether they are inside or outside the United States. The restriction also applies to foreign national employees working at Anthropic. As a result, the company has disabled both models for all customers to ensure compliance. Access to previous Anthropic models like Opus and Sonnet is not affected by this government order. The company highlighted that it had developed strong safeguards to reduce the possibility that Fable is misused for tasks related to cybersecurity. In fact, many developers are complaining that the safeguards are going overboard. Additionally, the company worked with the US government, the UK AISI, multiple private third-party organizations, and internal teams to red-team Fable’s safeguards for thousands of hours. Finally, Anthropic noted that no testers have yet been able to find a universal jailbreak on Fable 5. As expected, Anthropic disagrees that a narrow potential jailbreak should lead to the recall of a commercial model used by hundreds of millions of people. It warned that applying this standard across the AI industry could effectively halt new frontier model deployments. Anthropic concluded by mentioning that it is working to restore access to Fable 5 and Mythos 5 as soon as possible and plans to share more details within the next 24 hours.
    • Brave Browser 1.91.172 is out.
  • Recent Achievements

    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
    • Rookie
      Rimplesnort went up a rank
      Rookie
    • One Year In
      Markus94287 earned a badge
      One Year In
    • One Month Later
      Markus94287 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      503
    2. 2
      +Edouard
      176
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      92
    5. 5
      Steven P.
      79
  • Tell a friend

    Love Neowin? Tell a friend!