Why cant I access the methods within my base class in C#? - c#

I am trying to have my class number output the variable result from another class. however once run it displays. Error CS0103: The name 'result' does not exist in the current context. Can someone tell me how I can fix this? How can I call the method getMax correctly?
using System;
namespace Bank
{
class FindMax
{
public int setMax(int numOne, int numTwo)
{
int result;
if (numOne >= numTwo)
result = numOne;
else
result = numTwo;
return result;
}
}
class Number : FindMax
{
public void getMax()
{
Console.WriteLine(result);
}
}
class MainClass
{
public static void Main(string[] args)
{
FindMax mx = new FindMax();
Number n = new Number();
mx.setMax(20, 12);
n.getMax();
}
}
}

You defined result as a local variable inside setMax(), so getMax() cannot access it. So, you should fix the code:
class FindMax
{
protected int Result; // Not private, because Number (inherits from FindMax) should access it.
public int setMax(int numOne, int numTwo)
{
if (numOne >= numTwo)
Result = numOne;
else
Result = numTwo;
return Result;
}
}
class Number : FindMax
{
public void getMax()
{
Console.WriteLine(Result);
}
}

result is a local variable, and you can not access it from Number class. You should set it at a property of your base class:
using System;
namespace Bank
{
class FindMax
{
protected int max;
public void setMax(int numOne, int numTwo)
{
if (numOne >= numTwo)
max = numOne;
else
max = numTwo;
}
}
class Number : FindMax
{
public void getMax()
{
Console.WriteLine(max);
}
}
class MainClass
{
public static void Main(string[] args)
{
Number n = new Number();
n.setMax(20, 12);
n.getMax();
}
}
}

Because the variable in getMax is not defined.
You can do something like this
class Number : FindMax
{
public void getMax(int result)
{
Console.WriteLine(result);
}
}
and then call
var max = mx.setMax(20, 12);
n.getMax(max);

Related

Name '...' doesn't exit in current context

I am a beginner in C# right now and my task is to write in console all the details of a product. I have to use the struct. I made a Product struct.
The function writeProducts cannot see the prod1 and all of its details.
However I get an error CS0103 that the name doesn't exist in current context and I don't know where I made a mistake.
Sorry, English is not my native language.
namespace project
{
class Program
{
public struct Product
{
public string Name;
public string Type;
public double Pr1pc;
public double Pr1kg;
public int number;
}
static void Main(string[] args)
{
Console.Clear();
Product prod1;
//Prod1
prod1.Name = "Chlyb";
prod1.Type = "szt";
prod1.Pr1pc = 6.30;
prod1.number = 1;
writeProducts();
Console.ReadKey();
Main(args);
}
static void writeProducts()
{
Console.WriteLine("{0}. {0},{0}{0}", prod1.number, prod1.Name, prod1.Pr1pc, prod1.Type);
}
}
}
You declared the variable prod1 in the Main function, so it is not recognized in the writeProducts function. Try to send the prod1 as a parameter to writeProducts like that:
class Program
{
public struct Product
{
public string Name;
public string Type;
public double Pr1pc;
public double Pr1kg;
public int number;
}
static void Main(string[] args)
{
Console.Clear();
Product prod1 = new();
//Prod1
prod1.Name = "Chlyb";
prod1.Type = "szt";
prod1.Pr1pc = 6.30;
prod1.number = 1;
writeProducts(prod1);
Console.ReadKey();
Main(args);
}
static void writeProducts(Product prod)
{
Console.WriteLine("{0}. {0},{0}{0}", prod.number, prod.Name, prod.Pr1pc, prod.Type);
}
}
}
Also notice you need to use the new word when declaring prod1

Code Refactoring to remove the duplicate code

I have three methods in two classes in which two methods have the same code but with different inheritance. How can I reduce the duplicate codes by adding a new class? I have tried to simplify it with a simple sample. Hope the code makes sense. How can I refactor this? Any help on this much appreciated.
GetConnection.cs
public class GetConnection1 : LookupConnection1
{
public override int GetConnectionCount()
{
/* This method is same as that of the GetConnection2 class file but inherits from other
class named LookUpConnection1
Need to refactor this duplicate method */
int conCount = base.GetConnectionCount();
int value = GetAvailableConnections(conCount);
return value;
}
private int GetAvailableConnections(int conCount)
{
/* This method is same as that in GetConnection2. This method is
exact replica that is in GetConnection2 class
Need to refactor this duplicate method */
int value = 0;
for (int i = 0; i < conCount; i++)
value = GetConnection(value);
return value;
}
private int GetConnection(int value)
{
/* This is the method which differs from the GetConnection2 class. */
return value + 10;
}
}
GetConnection2 class:
public class GetConnection2 : LookUpConnection2
{
public override int GetConnectionCount()
{
/* This method is same as that of the GetConnection1 class file but inherits from other
class named LookUpConnection2
Need to refactor this method*/
int conCount = base.GetConnectionCount();
int value = GetAvailableConnections(conCount);
return value;
}
private int GetAvailableConnections(int conCount)
{
/* This method is same as that in GetConnection1. This method is
exact replica that is in GetConnection1 class
Need to refactor this duplicate method */
int value = 0;
for (int i = 0; i < conCount; i++)
value = GetConnection(value);
return value;
}
private int GetConnection(int value)
{
/* This is the method which differs from the GetConnection2 class. */
return value + 30;
}
}
LookupConnection1 class file
public class LookupConnection1 : BaseConnection
{
public override int GetConnectionCount()
{
return 20;
}
}
LookUpConnection2 class file
public class LookUpConnection2 : BaseConnection
{
public override int GetConnectionCount()
{
return 10;
}
}
BaseConnection class file
public abstract class BaseConnection
{
public abstract int GetConnectionCount();
}
public class Program
{
static void Main()
{
GetConnection1 connection1 = new GetConnection1();
GetConnection2 connection2 = new GetConnection2();
Console.Write(connection1.GetConnectionCount());
Console.Write(connection2.GetConnectionCount());
}
}
Thanks in Advance,
You have to create an unique LookupConnection class and move GetAvailableConnections and GetConnection methods to the LookupConnection class. Below is the refactored code, hope it helps you!!!
// Create a unique LookupConnection class
public class LookupConnection : BaseConnection
{
// Private field to hold the initial value
private readonly int _count;
// Pass the expected value through the constructor.
// That will allow you to pass values as needed in each LookupConnection inheritance.
public LookupConnection(int count)
{
_count = count;
}
// Override GetConnectionCount method to use
// the GetAvailableConnections defined in this class
public override int GetConnectionCount()
{
return GetAvailableConnections(_count);
}
// If you put GetAvailableConnections in the LookupConnection class
// you don't need to worry about what it does, because always it does the same.
// Make it virtual if later you want change its behavior.
protected virtual int GetAvailableConnections(int conCount)
{
int value = 0;
for (int i = 0; i < conCount; i++)
value = GetConnection(value);
return value;
}
// Add the GetConnection to the LookupConnection and make it
// virtual in order to override in the different GetConnection classes
protected virtual int GetConnection(int value)
{
return value;
}
}
// This is how your class will look like
public class GetConnection1 : LookupConnection
{
// Pass the value to the base constructor as needed
public GetConnection1 () : base(20)
{
}
// Here you can override the GetConnection and add the particular behavior for this class
protected override int GetConnection(int value)
{
return value + 10;
}
}
// This is how your class will look like
public class GetConnection2 : LookUpConnection
{
// Pass the value to the base constructor as needed
public GetConnection2 () : base(10)
{
}
// Here you can override the GetConnection and add the particular behavior for this class
protected override int GetConnection(int value)
{
return value + 30;
}
}
public class Program
{
static void Main()
{
GetConnection1 connection1 = new GetConnection1();
GetConnection2 connection2 = new GetConnection2();
Console.Write(connection1.GetConnectionCount());
Console.Write(connection2.GetConnectionCount());
}
}

How to fix this ISeries interface implementation in Class1?

I am developing a series of numbers starting from Setstart(2) function from ISeries interface. I tried to implement this interface in Class1 but it threw an error to me. And I am getting stuck at this error and not been able to figure out to fix this. What am I missing? Please help
I tried to make all functions in the interface public
I tried to remove public access specifier from interface
public interface ISeries {
void Setstart (int a);
int GetNext ();
void Reset ();
}
class Class1 : ISeries {
int val;
void Setstart (int a) {
val = a;
}
int GetNext () {
return val++;
}
void Reset () {
val = 0;
}
static void Main () {
Class1 c = new Class1 ();
c.Setstart (2);
Console.WriteLine (c.GetNext ());
c.Reset ();
Console.WriteLine ();
}
}
I expect the output to be 3 and 0 error is being generated
Your should try something like this.
Because you have to play with one variable so you have to make use of ref `keyword in this case.
and also you have to mark all the method inside a class as a public otherwise you were not be able to access those method inside main
Code:
using System;
namespace StackoverflowProblem
{
public interface ISeries
{
void Setstart(ref int value);
int GetNext(ref int value);
void Reset(ref int value);
}
public class Class1 : ISeries
{
public int val { get; set; }
public void Setstart(ref int value)
{
this.val = value;
}
public int GetNext(ref int value)
{
value = value + 1;
this.val = value;
return this.val;
}
public void Reset(ref int value)
{
// Resetting val.
value = 0;
this.val = value;
}
}
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
int value = 2;
c.Setstart(ref value);
Console.WriteLine(" " + c.GetNext(ref value));
c.Reset(ref value);
Console.WriteLine();
}
}
}
Output:
val++ will incriment after returning the current value, ++val will increment first then return the value, you should now get 3, also make it proper scoped to access the methods from outside
class Class1 : ISeries {
int val;
public void Setstart (int a) {
val = a;
}
public int GetNext () {
return ++val;
}
public void Reset () {
val = 0;
}
static void Main () {
Class1 c = new Class1();
c.Setstart(2);
Console.WriteLine (c.GetNext());
c.Reset();
Console.WriteLine ("");
}
}
You need to make your methods public to be accessible outside from class which is missing other than that your code looks fine.
You need to make all the 3 methods public as per your scenario like :
public void Setstart (int a) {
and you will need to first add 1 and then return to get 3 as output as val++ will return the current value and then increment it by 1:
public int GetNext () {
// return val++; // Post increment will not work according to question.
val = val + 1;
return val;
}
Your class with complete implementation of Interface would be like following:
public class Class1 : ISeries {
int val;
public void Setstart (int a) {
val = a;
}
public int GetNext () {
val = val + 1;
return val;
}
public void Reset () {
val = 0;
}
}

How to Count the object instace using Static property in C#.(Not using Costrutor0)

I want to count the number of instance and I want to call The set accessor or Modifiers of property in c3 at the time of object creation can I?
call set at object
class a {
private static int x;
public static int X {
get {
return x;
}
set { //Call This area while oblect Creation }
}
}
class Program {
static void Main(string[] args) {
a o = new a();
a ob = new a();
Console.WriteLine("Count is: " + a.X);
}
}
To my mind, the only reasonably approach here is:
class a {
private static int x;
public static int X { get { return x; } }
public a()
{
Interlocked.Increment(ref x);
}
...
}
Now yes, the question title says "not using constructor", but: if you want to count how many instances of a type have been created - the appropriate place to put that code is in the constructor.
The Interlocked.Increment(ref x); could be replaced with x++; if you don't care about the answer being right when using multiple threads.
You could also satisfy the "not using constructor" by using a factory method:
private a() {}
public static a Create()
{
Interlocked.Increment(ref x);
return new a();
}
but if you do that, the new a() in the Main() method no longer works, and needs to be changed to a.Create().
If you don't want to use a constructor to increment your x variable you can call a static method which increments the value of x and creates a new instance of your a class:
static void Main(string[] args)
{
a o = a.incrementX();
a ob = a.incrementX();
Console.WriteLine("Count is: " + a.X);
}
The static method incrementX is defined in your class:
class a
{
private static int x;
public static int X
{
get { return x; }
set { x = value;}
}
public static a incrementX()
{
X++;
return new a();
}
}
use this:
class a
{
private static int x;
public static int X
{
get { return x; }
set { //Call This area while oblect Creation }
}
}
class Program
{
static void Main(string[] args)
{
a o = new a();
a.X += 1;
Console.WriteLine("Count is: " + a.X);
}
}
You access static field without initializing the object and so you set it's value.

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

Categories

Resources