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.
Related
i am a C# beginner, so for now most of my code is inside the Main() method. I want to make my Program more object oriented so I want to move code from Main method to another class reliably(so i can do it with other programs as well).
static void Main()
{
int xLentgh = 20;
int yLength = 20;
Map.MapBuilder(xLentgh,yLength);
int oldPositionX = 0;
int oldPositionY = 0;
int newPositionX = 0;
int newPositionY = 0;
if (oldPositionX == 0)
{
Map.WriteAt(".",newPositionX, newPositionY);
}
for (int i = 0; i < 100; i++)
{
ConsoleKeyInfo KeyStroke;
KeyStroke = Console.ReadKey();
switch (KeyStroke.Key)
{
case ConsoleKey.RightArrow:
{
if (newPositionX < xLentgh-1)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionX++;
}
break;
}
case ConsoleKey.LeftArrow:
{
if (newPositionX > 0)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionX--;
}
break;
}
case ConsoleKey.UpArrow:
{
if (newPositionY > 0)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionY--;
}
break;
}
case ConsoleKey.DownArrow:
{
if (newPositionY < yLength-1)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionY++;
}
break;
}
default: break;
}
Map.WriteAt(".",newPositionX, newPositionY);
Map.WriteAt(" ",oldPositionX, oldPositionY);
}
}
In this code I create a "map" and using the switch statement in the for loop to "track" the position of the cursor. How do I write this code in a new class? I dont know where to start
You can try to create a class named as you want (we will call it RandomNameClass) by declaring it outside of the bloc class Program {}.
You should have something like this :
namespace NameYouGaveToProject
{
class RandomNameClass
{
}
class Program
{
static void Main(string[] args)
{
// Your actual code here
}
}
}
Above or under is fine but prefer having the class Program at the bottom if you write all your code in one file.
There you have your first custom class! Now try to add some functions in it. If you haven't learn about instantiating a class yet, just don't forget to add public static before the returning type of your function.
Example of what you could have :
namespace NameYouGaveToProject
{
class RandomNameClass
{
// Function that doesn't return anything, returns "void"
public static void SayHi()
{
Console.WriteLine("Hi!");
}
// Function that returns a string
public static string ReturnHi()
{
return "Hi!";
}
}
class Program
{
static void Main(string[] args)
{
// Your actual code here
}
}
}
And then you can call them by typing the name of the class, followed by a point and then the name of the function and "()" if there are no parameters to this function (there aren't in my example).
The syntax would be :
// Call the void function
RandomNameClass.SayHi();
// Call the function returning a string
string testVariable = RandomNameClass.ReturnHi();
Note that you can call as often as you want every function
And voilĂ ! You know the basics of creating a class and call functions from this class! Next thing you should learn is how to make functions properly, and then instantiating a class and manage it's content
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
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;
}
I'm making a game using Monogame, and I've been trying to figure out how to implement a function that acts similarly to AS3's and GML's with statement.
So far I have a system that works, but not entirely the way I want it to. I store my GameObjects in a Dictionary of Lists. This is so I can get to the specific type of object I want to access without having to loop through a list of ALL objects. The key used is the name of the type.
public static Dictionary<string, List<GameObject>> All =
new Dictionary<string, List<GameObject>>();
I access all of a specific type of object using AllOf. If a List containing that type exists in the Dictionary, it returns that List, else it returns an empty list.
public static List<GameObject> AllOf(Type type)
{
string key = type.Name;
if(All.ContainsKey(key))
{
return All[key];
}
return new List<GameObject>();
}
An example of how these are implemented
public override void Update(GameTime gameTime)
{
List<GameObject> list = Instance.AllOf(typeof(Dummy));
for(int i = 0; i < list.Count; i++)
{
list[i].Update(gameTime);
list[i].foo += bar;
}
}
But I'd rather use something similar to the AS3/GML with statement, which would also allow for other, non-member codes to be executed.
with(typeof(Dummy))
{
Update(gameTime);
foo += bar;
int fooBar = 2;
someObject.someMemberFunction(fooBar);
}
Is there a way to accomplish this? My end goal is just to make my code look a little cleaner, and make it easier to make a lot of changes without having to type out a for loop each time.
No such syntax exists in C#, but you can access methods within the for that have nothing to do with the collection:
public override void Update(GameTime gameTime)
{
List<GameObject> list = Instance.AllOf(typeof(Dummy));
for(int i = 0; i < list.Count; i++)
{
list[i].Update(gameTime);
list[i].foo += bar;
int fooBar = 2;
someObject.someMemberFunction(fooBar);
}
}
Note that you can also use foreach, which is a little cleaner if you don't need the indexer:
foreach(var item in list)
{
item.Update(gameTime);
item.foo += bar;
int fooBar = 2;
someObject.someMemberFunction(fooBar);
}
try
using(Object myObject = new Object()){
}
i think this might be what your looking to use?
I have a small solution for this use case. This may be a bit of a necropost, but it is a pretty neat solution. Additionally, I think all of the C# features that are required existed back when this question was asked.
You can do something very similar to the GML with(x){} by using some form of delegate as a parameter to a static method, and passing a lambda as that parameter. The function can even be genericised, and you can call it without the class name by the using static statement. You will need to explicitly provide the typed/named parameter, but it is possible. You would need to hook it up to your own types, but the general idea is:
namespace NiftyStuff {
public static class With {
public static void with<T>(Action<T> proc) where T : GameObj {
var typeName = typeof(T).Name;
foreach (var item in GameObj.AllOf(typeName)) { proc((T)item); }
}
}
public class GameObj {
private static Dictionary<string, List<GameObj>> All = new Dictionary<string, List<GameObj>>();
public static List<GameObj> AllOf(string name) {
return All.ContainsKey(name) ? All[name] : null;
}
public static void Add(GameObj foo) {
string typeName = foo.GetType().Name;
List<GameObj> foos = All.ContainsKey(typeName) ? All[typeName] : (All[typeName] = new List<GameObj>());
foos.Add(foo);
}
public float x, y, angle;
public GameObj() { x = y = angle = 0; }
public void Destroy() { AllOf(GetType().Name)?.Remove(this); }
}
public class Enemy : GameObj {
public float maxHealth, curHealth;
public Enemy() : base() { maxHealth = curHealth = 300; }
public Enemy(float health) : base() { maxHealth = curHealth = health; }
public bool Damage(float amt) {
if (curHealth > 0) {
curHealth -= amt;
return curHealth <= 0;
}
return false;
}
}
public class Pumpkin : GameObj {
public bool exists = false;
public Pumpkin() : base() { exists = true; }
public bool LookAt() { return (exists = !exists); }
}
}
Actually using the above code would work as follows:
using NiftyStuff;
using static NiftyStuff.With;
//...
with ((Enemy e) => {
if (e.Damage(50)) {
Log("Made a kill!"); // Whatever log function you have...
}
});
with ((Pumpkin p) => {
if (p.LookAt()) {
Log("You see the pumpkin");
} else {
Log("You no longer see the pumpkin");
}
});
While not exactly like GML's with statement, it would at least let you run code against all of the registered objects of some type.
One important note is that you can't destroy objects inside of a with this way (due to concurrent modification of a collection while iterating it). You would need to collect all objects to be destroyed, and then remove them from the list in All, typically in a game loop this is done at the end of a frame.
Hope this helps, despite being 2 years out of date.
****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.