Using property setting to make additions and retrieval - c#

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;
}

Related

Struggling with how methods and classes interact

I'm new to learning C# and am trying to implement the below code however, I am unable to do so, receiving the error "A namespace cannot directly contain members such as fields or methods".
namespace Grades
{
public string LetterGrade
{
get
{
string result;
if (RoundResult(AverageGrade) >= 90)
{
result = "A";
}
else if (RoundResult(AverageGrade) >= 80)
{
result = "B";
}
else if (RoundResult(AverageGrade) >= 70)
{
result = "C";
}
else
{
result = "F";
}
return result;
}
}
private double RoundResult(double result)
{
double r;
r = Math.Round(result);
return r;
}
public class GradeStatistics
{
public float AverageGrade = 50;
public float HighestGrade = 78;
public float LowestGrade = 11;
}
}
What I am trying to accomplish is to create a method called "RoundResult" which will round the "AverageGrade" result. I am merely doing this as an experiment to try and understand how methods interact with each other.
The biggest hurdle I am facing while learning C# is in regards to methods and classes, how to use them correctly, when to place them within an existing class or create there own separate class etc. If someone has any recommended resource that goes into extensive step by step detail on how to implement methods and classes, that would be greatly appreciated.
Edit: Thanks to Reputation Farmer and wazdev for their answers. I'd like to add an additional question....
Why is the "GradeStatistic" method a valid method to call the "AverageGrade" from within the same class yet my "RoundResult" method can not be within the same class?
This error message is occurring because you have two methods directly inside your namespace declaration- they need to be wrapped inside a class.
One possible solution is to create a "GradeCalculator" class and put your two methods inside that ... please note that this is not an optimal solution, but I've tried to modify as little as posssible:
namespace Grades
{
public class GradeCalculator
{
public string LetterGrade
{
get
{
string result;
if (RoundResult(GradeStatistics.AverageGrade) >= 90)
{
result = "A";
}
else if (RoundResult(GradeStatistics.AverageGrade) >= 80)
{
result = "B";
}
else if (RoundResult(GradeStatistics.AverageGrade) >= 70)
{
result = "C";
}
else
{
result = "F";
}
return result;
}
}
private double RoundResult(double result)
{
double r;
r = Math.Round(result);
return r;
}
}
public static class GradeStatistics
{
public static float AverageGrade = 50;
public static float HighestGrade = 78;
public static float LowestGrade = 11;
}
}
As the error says, namespace can't contain methods. You should put them inside a class:
namespace Grades
{
public static class GradeUtil {
public static string LetterGrade { ... }
private static double RoundResult(double result) { ... }
}
public class GradeStatistics
{
public float AverageGrade = 50;
public float HighestGrade = 78;
public float LowestGrade = 11;
}
}
Note the word static. It allows you to call a method without object instance. I.e. you can write GradeUtil.LetterGrade .... It's unclear, cut looks like this is what you intended.

C# for students book exercise 10.2 (Book by Douglas Bell)

I am reading this book to self teach myself C#. However, I ran across a problem that I just can't figure out a way to tackle.
The question asks me:
Write a piece of program that remembers the value and compares them as a class. This class has a method NewValue and properties LowestValue and HighestValue.
I understand the question but it asks me to use a track bar which I can't seem to understand how can i store the minimum/maximum value that was previously selected on the trackbar.
My class looks like this:
class AmplifierDisplay
{
private int Low, High;
public AmplifierDisplay()
{
Low = 0;
High = 0;
}
public void NewValue()
{
Low = Math.Min(Low, High);
High = Math.Max(Low, High);
}
public int LowestValue
{
get
{
return Low;
}
set
{
Low = value;
}
}
public int HighestValue
{
get
{
return High;
}
set
{
High = value;
}
}
}
It sounds like you'll need two things:
1) A Comparer implementation to work out the difference between two measurements
2) A Memento pattern implementation to provide a history of the values
Upon each move event, store a memento in some kind of structure such as a List or a Queue. This "NewValue" class looks like a basis for the Memento anyway.
See Comparer and Memento
I found the answer!!! :D
Here is the class code:
class AmplifierDisplay
{
private int Low, High;
public AmplifierDisplay()
{
Low = 0;
High = 0;
}
public void NewValue(int newValue)
{
Low = Math.Min(Low, newValue);
High = Math.Max(High, newValue);
}
public int LowestValue
{
get
{
return Low;
}
set
{
Low = value;
}
}
public int HighestValue
{
get
{
return High;
}
set
{
High = value;
}
}
}
This is the code in the main program:
AmplifierDisplay amplify = new AmplifierDisplay();
private int newValue;
public Chapter10Ex2()
{
InitializeComponent();
amplify.HighestValue = 0;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
newValue = trackBar1.Value;
}
private void MouseUp(object sender, MouseEventArgs e)
{
amplify.NewValue(newValue);
lblMinMax.Text = amplify.LowestValue.ToString() + " , " + amplify.HighestValue.ToString();
}

C# Mock a Class With an Internal Property Setter

I am trying to build a unit test.
The class Position is implemented in a third party library. But for my unit test I need the Size property to be set to a specific value.
public class Position
{
private double _size;
private double Size
{
get
{
return _size;
}
internal set
{
_size = value;
}
}
}
I read this post: How do you create a unit-testing stub for an interface containing a read-only member?
but could not figure out how to make it work for me.
This is the class under test (just a simplified example). The posargument in the CalcPositionMetric() method must be of type Position:
public class PositionMetrics
{
public PositionMetrics()
{}
public double CalcPositionMetric(Position pos)
{
return 2 * pos.Size;
}
}
Here is a piece of my unit test:
using NUnit.Framework;
using NMock;
[TestFixture]
public class PositionUnitTests
{
[Test]
public void TestPosition()
{
Mock<Position> tmpPosMock = mFactory.CreateMock<Position>();
tmpPosMock.Expects.One.GetProperty(v => v.Size).WillReturn(7); /* !!! Exception !!! System.ArgumentException : mock object position has a getter for property Size, but it is not virtual or abstract */
/* Execute Test with tmpPositions*/
PositionMetrics pm = new PositionMetrics();
double result = pm.CalcPositionMetric(tmpPosMock.MockObject)
Assert.AreEqual(14, result);
}
}
But as you can see I get an exception. Could somebody help me to resolve this problem? Any other solutions are also welcome!
Cheers
Konstantin
New answer for the updated question I suggest you to introduce some kind of a proxy interface for that. See the code below:
interface IPosition {
int Size { get; }
}
class Position { //in 3rd party lib
public int Size {
get { return 5; }
}
}
class RealPosition : IPosition { //use this as your real object instead of using Position directly
private Position position;
public RealPosition(Position position) {
this.position = position;
}
public int Size {
get { return position.Size; }
}
}
class MockPosition : IPosition { //use this for testing
public int Size{ get; set; }
}
public class Program {
static void Main(string[] args) {
var pos = new MockPosition { Size = 7 };
Console.WriteLine(Calc(pos)); //prints 14
Console.ReadLine();
}
static int Calc(IPosition pos) { //change your method signature to work with interface
return pos.Size * 2;
}
}
Old answer If the class is not sealed you don't need any mocking libraries. Just use the new modifier for the required properties like this:
class Position {
public int Size { get { return 5; } }
}
class MockPosition : Position {
public new int Size { get; set; }
}
....
var mock= new MockPosition();
mock.Size = 7;
To use these items in some sort of list you'll have to cast them like this:
var items = new List<Position>();
for (int i = 0; i < 5; i++) {
items.Add(new MockPosition { Size = i });
}
foreach (var item in items.Cast<MockPosition>()) {
Console.Write("{0}\t", item.Size); //prints 0 1 2 3 4
}
If it is sealed and the property is not virtual than you'll have to use some other techniques, Moq (which I guess you are using) does not allow that

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();
}
}

Problem with Constructors

****Just below is my winform client inst with one parameter constructor within the class.****
private void button1_Click(object sender, EventArgs e)
{
string s1 = textBox1.Text;
int x1 = Convert.ToInt32(s1);
int X= x1;
ExternalTest ob = new ExternalTest(X);
string s2 = Convert.ToString(ob.Y);
ob.Y = 0;
textBox2.Text = s2;
And below this is my class that i added to the project
The code below is an added class within the assembly. If i tried to make it a class library and and add addreference - it will not build.
class ExternalTest
{
private int _x;
// protected new int x
// {
// get { return _x; }
// set {_x = value ;}
// }
private int y;
public int Y
{
get {return y = Mult(_x); }
set { }
}
internal int Mult(int _x)
{
y = _x + 51;
return y;
}
public ExternalTest(int X)
{
_x = X;
}
}
}
Your class is not public by default. You must add public to the definition of the class when you're using it in an external library, or the WinForms client will not be able to see it.
EG:
public class ExternalObj
{
// ...
}
Based on the fact that you are getting a compile error only when this class is in an external library, and the numerous times I've forgotten to add public when I've needed it myself, I'm thinking this is probably the issue.

Categories

Resources