Get and Set condition value - c#

I'm trying to learn get and set and I can't seem to figure out this problem. I have a condition to set a value, only set the value if it's greater than "_num = 10".
My problem is, even if the value is under 10 the value still sets. What am I missing? I should get an error with this code, but I'm not getting it...
thanks for ur time.
using System;
namespace Namespace
{
internal class Program
{
private static void Main(string[] args)
{
int x = Items.Sum = 5;
Console.WriteLine(x);
Console.ReadKey();
}
}
public static class Items
{
private static int _num = 10;
public static int Sum
{
get { return _num; }
set
{
if (value > _num)
_num = value;
}
}
}
}

Because your have property as static and it will be set even before the constructor gets called. That’s why it is returning 10.
Please declare the main method as public not private.

Related

C# unused Property crash my code

The Code prints different answer depending on debugging or not. What did i wrong?
class Program
{
static void Main(string[] args)
{
Feld feld = new Feld();
feld.Setze = 5;
Console.WriteLine(feld.Besetzt);
Console.Read();
}
}
public class Feld
{
public int figur;
public bool Besetzt { get => (figur != 0) ? true : false; }
public int Setze { set => figur = value; }
public int Nehmen { get { int cur = figur; figur = 0; return cur; } }
}
If i delet the last Property it work's but why?
To expand on the existing comments and answers: your Nehmen property has nasty side-effects:
public int Nehmen { get { int cur = figur; figur = 0; return cur; } }
every time the value is read, it resets itself to zero. This is a very bad idea - property get accessors should not have unexpected side-effects. Large parts of the tooling expect reading Nehmen to not do that, and the IDE / debugger will often try to help you understand your data by querying the properties to show you.
This means that when the debugger is trying to help you, it is actually resetting the values.
So: make Nehmen a method:
public int Nehmen()
{
int cur = figur;
figur = 0;
return cur;
}
The system expects methods to have side-effects, so does not invoke them to "help" you.
The only valid side-effects of property get accessors is to invoke lazy-loading / initialization side effects.
You must have the variable Nehmen in the Watch Window in Visual Studio... Or trying to access it in other way

Why am I getting this StackOverFlowException

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private int myFaveNumber; //fields
private const int myLeastFaveNumber = 5;
private string secretPassword = "Pickle";
public int MyFaveNumber
{
get
{
return MyFaveNumber;
}
set
{
if (value > 0)
MyFaveNumber = value;
else
myFaveNumber = 10;
}
}
public int Math()
{
return myFaveNumber - myLeastFaveNumber;
}
public Test()
{
Console.WriteLine("Secret password is " + secretPassword);
}
public Test(string two)
{
Console.WriteLine("The full password is {0}", two);
}
}
class Program
{
static void Main(string[] args)
{
Test quick = new Test();
Console.WriteLine(quick.ToString());
quick.MyFaveNumber = 5;
Console.WriteLine(quick.Math());
Test quicky = new Test("Drill");
Console.ReadKey();
}
}
}
I am messing around as a beginner, and am wondering why I am getting a "Process is terminated due to StackOverflowException". If you could help me figure this out that would be great. Also any tips are always welcome.
It should be myFaveNumber not MyFaveNumber = value;
set
{
if (value > 0)
myFaveNumber = value;
else
myFaveNumber = 10;
}
The problem is in this part:
public int MyFaveNumber
{
get
{
return MyFaveNumber;
}
...
}
You've set the MyFaveNumber property to return itself. Likewise, in the setter:
set
{
if (value > 0)
MyFaveNumber = value;
else
myFaveNumber = 10;
}
You (conditionally) assign MyFaveNumber, causing the setter to call itself. Both of these scenarios will cause the property to recursively call its getter/setter over and over again until the program crashes.
You need to be getting/setting the private backing field myFaveNumber instead:
public int MyFaveNumber
{
get
{
return myFaveNumber;
}
set
{
if (value > 0)
myFaveNumber = value;
else
myFaveNumber = 10;
}
}
Consider property as a function.
When you write this functions
public int GetMyProperty()
{
return GetMyProperty();
}
public void SetMyProperty(int value)
{
if (value > 0)
SetMyProperty(value);
}
You will obviously recognize that there is possibility in infinite recursive call which will "blow up" your stack(default size of the stack for .NET applications is 1 MB). So you increase size of the stack with every recursive call which happened in you program when you execute.
quick.MyFaveNumber = 5;
And you will get same exception in case when you will try to read value of the property
Console.WriteLine(quick.MyFaveNumber);
So correct way of using properties assign values to the underlying private field when needed validation is done.
private int _myProperty;
public int MyProperty
{
}

Using property setting to make additions and retrieval

In my program, I am making currency addition from a for...loop. It is working fine. But I am not sure if what has been done is correct and in accordance with C#.
class Program {
private double _amount;
public double amount {
get {
return _amount;
}
set {
_amount = value;
}
}
static void Main(string[] args) {
Program p = new Program();
for (int i = 1000; i < 1300; i++) {
double y = 30.00;
double x = y + p._amount;
p._amount = x;
}
Console.WriteLine(p._amount.ToString());
Console.ReadLine();
}
}
I have reduced the size of the code. In effect, however, there are several if clauses within the for...loop which I do the calculations.
I would like to thank anyone who could point out any inconsistency with C# coding principles.
The first thing is to use meaningful names, so program could be given a more
meaningful name.
Modularise your code (create a separate class from your program) and use the recommended coding practices by MSDN for C#.
class Calculation
{
public double Amount { get; set; }
public double run(double y)
{
// No need to start at 1000.
for(int i = 0; i < 300; i++)
{
Amount += y;
}
return Amount;
}
}
class Program
{
static void Main(string[] args)
{
Calculation calculation = new Calculation();
// pass your variable as a parameter into a class function.
var y = 30.0;
Console.WriteLine(calculation.run(y).ToString());
// Console.ReadLine(); use control F5 to prevent console window from closing.
}
}
C# Coding Conventions (C# Programming Guide)
I would recommend changing this code:
public double amount
{
get
{
return _amount;
}
set
{
_amount = value;
}
}
with this:
public double getamount()
{
return _amount;
}
public void setamount(int value)
{
_amount = value;
}

Why does using delegates in c# give a stackoverflowexception

When I came across delegates I wrote this really simple program just to practice. when I run it there is a stackoverflowexception. so if anyone can tell me what is wrong with this piece of code please do cause I have wasted a lot of time on trying to make it work but couldn't.
Here is the code:
using System;
public delegate void click();
class test
{
public click flare;
public double length;
public double Length
{
get
{
return Length;
}
set
{
Length = value;
flare();
}
}
}
class glance
{
public glance(ref test a)
{
a.flare = blank;
}
public void blank()
{
Console.WriteLine("this is blank");
}
}
class Program
{enter code here
static void Main(String[] args)
{
test know = new test();
glance x = new glance(ref know);
know.Length = 10;
}
}
It has nothing to do with delegates. You are calling setter method inside of setter in Lenght property and that causes the exception.Use the backing field you created for your property:
public double Length
{
get
{
return length;
}
set
{
length = value;
flare();
}
}

C# allow public incrementation of property, but not explicit seting

What I want to do is allow the public incrementation of an integer value within my class, but not allow it to be publicly set explicitly.
I know that I can create a function like this:
void IncrementMyProperty()
but I'd like to allow the user to just do this:
MyClass.Property++;
without allowing this:
MyClass.Property = <SomeInt>;
It's merely for convenience. I'm just wondering if there is any way to do it.
Here's an example:
class MyClass
{
private int _count;
public int Count
{
get { return _count; }
private set { _count = value; }
}
public void AddOne()
{
_count++;
}
}
class Program
{
static void Main()
{
MyClass example;
for (int i = 0; i < 10; i++)
example.Count++;
}
}
Obviously this won't compile. It's just to show what I'd like to do.
Well, it's possible, but the solution is pretty ugly.
You can create a type that overloads the ++ operator, and make a property of that type where the setter does nothing. That will allow you to use the ++ operator on the property, but it's not possible to actually set the property using the property setter:
class MyValue {
public int Value { get; private set; }
public MyValue(int value) {
Value = value;
}
public static MyValue operator ++(MyValue v) {
v.Value++;
return v;
}
}
class MyClass {
private MyValue _count = new MyValue(0);
public MyValue Count {
get { return _count; }
set { }
}
}
Usage:
MyClass c = new MyClass();
c.Count++;
Console.WriteLine(c.Count.Value); // outputs 1
So... using the ++ operator in that way is not a good solution. Normally you don't have a setter that does nothing, that will only be confusing. Having a method that increases the counter is not as short as writing ++, but it won't be confusing as long as you name it so that it's clear what it does.
There's no way. MyClass.MyProperty++ literally translates to MyClass.MyProperty = MyClass.MyProperty + 1, which uses a "setter" and if you allow a "setter" accessor then you would allow, for example, MyClass.MyProperty = <any value>;
not if you increment the int property. but you could write example++ and overload the ++ operator for your class to increment Count, while removing its setter.

Categories

Resources