• 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

    • Weekend PC Game Deals: Anno 117, Final Fantasy VII, Rematch, and more by Pulasthi Ariyasinghe Weekend PC Game Deals is where the hottest gaming deals from all over the internet are gathered into one place every week for your consumption. So kick back, relax, and hold on to your wallets. The Epic Games Store's mystery giveaways may have ended, but its regular freebies didn't miss a step this week. The double drop was for copies of Warhammer 40K Speed Freeks and The Ouroboros King. Speed Freeks lands for multiplayer racing fans, but with plenty of competitive shooting elements too. You will be piloting Ork buggies, tanks, and aircraft modeled after the popular tabletop miniatures while trying to complete objectives and pass finish lines. Next, Ouroboros King is a crossover between chess and tactical roguelikes, offering the chance to create your own army with special rules to beat incoming foes on the board. The double giveaway on the Epic Games Store will be available until June 11, and replacing it will be Citizen Sleeper and ROBOBEAT. The Humble Store brought a new charity bundle to check out this week too. Landing with the name The Complete Inkle Library, this is a large collection of interactive narrative puzzle games from the publisher Inkle. This begins with Heaven's Vault, four parts from the Sorcery series, 80 Days, Overboard, and Pendragon: Narrative Tactics within the starting tier for $9. Hopping up a step to the $12 tier gets you TR-49, Expelled, and A Highland Song for paying at least $12. If you go for the $20 tier, you get four e-books from the Heaven's Vault series. The bundle has almost three weeks on its counter before it goes away. Big Deals There is a larger than normal amount of weekend specials happening this time, including multiple publisher deals, franchise discounts, and indie gems to grab. With those and more, here's our hand-picked big deals list for the weekend: Anno 117: Pax Romana – $44.99 on Steam Clair Obscur: Expedition 33 – $39.99 on Steam Timberborn – $27.99 on Steam EARTH DEFENSE FORCE 6 – $26.39 on Steam Rust – $19.99 on Steam FINAL FANTASY VII REBIRTH – $19.99 on Steam Street Fighter 6 – $19.99 on Steam Returnal – $19.79 on Steam Shape of Dreams – $17.49 on Steam Far Cry 6 – $14.99 on Steam Assassin's Creed Valhalla – $14.99 on Steam Quarantine Zone: The Last Check – $14.99 on Steam REMATCH – $14.99 on Steam EA SPORTS FC 26 – $13.99 on Steam FINAL FANTASY VII REMAKE INTERGRADE – $13.99 on Steam Magicraft – $12.79 on Steam Cult of the Lamb – $12.49 on Steam Dying Light 2: Reloaded Edition – $11.99 on Steam Cuphead – $11.99 on Steam Assassin's Creed Odyssey – $11.99 on Steam Hunt: Showdown 1896 – $11.99 on Steam Sektori – $11.99 on Steam Just Shapes & Beats – $11.99 on Steam Gunfire Reborn – $10.99 on Steam 33 Immortals – $9.99 on Epic Store Baby Steps – $9.99 on Steam Sifu – $9.99 on Steam Hearts of Iron IV – $9.99 on Steam DREDGE – $9.99 on Steam DAVE THE DIVER – $9.99 on Steam Pacific Drive – $9.89 on Steam Mycopunk – $9.74 on Steam Sons Of The Forest – $8.99 on Steam Jotunnslayer: Hordes of Hel – $8.99 on Steam Nuclear Throne – $8.99 on Steam Mechabellum – $8.99 on Steam Deep Rock Galactic: Survivor – $8.44 on Steam TerraTech Legion – $7.99 on Steam Inscryption – $7.99 on Steam Assassin's Creed Unity – $7.49 on Steam Minishoot' Adventures – $7.49 on Steam The Stanley Parable – $7.49 on Steam Oxygen Not Included – $7.49 on Steam Megabonk – $6.99 on Steam Look Outside – $5.99 on Steam Vampire Hunters – $5.24 on Steam MOTHERGUNSHIP – $4.99 on Steam My Friend Pedro – $3.99 on Steam The Messenger – $3.99 on Steam Vampire Survivors – $3.74 on Steam Brotato – $2.99 on Steam Enter the Gungeon – $2.99 on Steam Loop Hero – $2.99 on Steam GRIS – $2.99 on Steam Exit the Gungeon – $2.49 on Steam Hitman: Absolution – $1.99 on Steam CARRION – $1.99 on Steam Don't Starve Together – $1.49 on Steam Golf With Your Friends – $1.49 on Steam Hotline Miami – $0.99 on Steam The Ouroboros King – $0 on Epic Store Warhammer 40K Speed Freeks – $0 on Epic Store DRM-free Specials Hopping over to the DRM-free deals, the GOG store has plenty of discounts running this weekend too. Here are some highlights: Fallout 4: Game of the Year Edition - $15.99 on GOG Fallout: New Vegas Ultimate Edition - $9.99 on GOG Disco Elysium - The Final Cut - $9.99 on GOG Crysis - $9.99 on GOG Tyranny - Standard Edition - $7.49 on GOG Frostpunk: Game of the Year Edition - $7.35 on GOG Banished - $6.79 on GOG Fallout 3: Game of the Year Edition - $6.59 on GOG The Forgotten City - $6.25 on GOG The Age of Decadence - $5.99 on GOG SimCity 3000 Unlimited - $4.99 on GOG Assassin's Creed: Director's Cut - $4.99 on GOG SimCity 4 Deluxe Edition - $3.99 on GOG Vampyr - $3.99 on GOG Torchlight II - $3.99 on GOG Deus Ex GOTY Edition - $3.49 on GOG Primordia - $3.09 on GOG Theme Hospital - $2.99 on GOG SimCity 2000 Special Edition - $2.99 on GOG Total Annihilation: Kingdoms + Iron Plague - $2.99 on GOG Deus Ex: Human Revolution - Director’s Cut - $2.99 on GOG Master of Orion 1+2 - $2.39 on GOG Prince of Persia: The Sands of Time - $1.99 on GOG Prince of Persia: Warrior Within - $1.99 on GOG EVERSPACE - $1.99 on GOG Total Annihilation: Commander Pack - $0.99 on GOG Keep in mind that availability and pricing for some deals could vary depending on the region. That's it for our pick of this weekend's PC game deals, and hopefully, some of you have enough self-restraint not to keep adding to your ever-growing backlogs. As always, there are an enormous number of other deals ready and waiting all over the interwebs, as well as on services you may already subscribe to if you comb through them, so keep your eyes open for those, and have a great weekend.
    • 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.
  • Recent Achievements

    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • 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
  • 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!