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;
}
}
Related
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());
}
}
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);
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.
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
Yeah, I tried to make the title smaller, but I couldn't.
I'm very new to reflection, so I'm struggling with a problem that I don't know if it's even possible to solve.
I'll use some simple delegate example to describe it.
public void Main() {
var manager = new EvManager();
var class1 = new Class1(manager);
var class2 = new Class2(manager);
manager.ExecuteIt(5, 12);
/*
This outputs:
In Class1 -> 17
In Class2 -> 18
*/
}
public class EvManager {
public delegate void SumDelegate(int a, int b);
private SumDelegate sum;
public void AddDelegate(SumDelegate s) {
sum += s;
}
public void ExecuteIt(int a, int b) {
sum.Invoke(a, b);
}
}
public class Class1 {
public Class1(EvManager m) {
m.AddDelegate(MySum);
}
private void MySum(int a, int b) {
Console.Write("In Class1 -> " + (a + b));
}
}
public class Class2 {
public Class2(EvManager m) {
m.AddDelegate(MyOtherSum);
}
private void MyOtherSum(int a, int b){
Console.Write("In Classe2 -> " + (a + b));
}
}
Okay, that's the example. What do I want from it? I want, through the EvManager "sum" delegate property be able to access the concrete implementations of all the methods that it invokes.
This is basically what I want:
class EvManager {
private SumDelegate sum;
public void ExecuteIt(int a, int b) {
var invocationList = sum.GetInvocationList();
foreach (var m in invocationList) {
// m is a reference to the annonymous call.
// Through reflection, I want to access the concrete method name.
// In this case, the first iteration "MySum", and the second "MyOtherSum"
// Is this possible?
// Like...
// var concreteMethodName = m.GetMethod().ConcreteCallerType.GetMethod(m.GetConreteMethodName());
// Or something like that?
}
}
}
Hope I made my problem clear, this is killing me.
The Method property holds the information about the real method:
var mName = m.Method.Name;
You can add the following method to EvManager:
public void ListDelegates()
{
foreach (var m in sum.GetInvocationList())
{
Console.WriteLine(m.Method.Name);
}
}
Calling it will give you what you want:
MySum
MyOtherSum
Take a look here on a Delegate class reference.
Actually, it is very simple. Use the Method property.
Check this code:
using System;
namespace ConsoleApplication2
{
public class EvManager
{
public delegate int SumDelegate(int a, int b);
private SumDelegate sum;
public void AddDelegate(SumDelegate s)
{
sum += s;
}
public void ExecuteIt(int a, int b)
{
foreach (var m in sum.GetInvocationList())
{
Console.WriteLine("{0}({1}, {2}) = {3}", m.Method.Name, a, b, m.DynamicInvoke(a, b));
}
}
}
public class Class1
{
public Class1(EvManager m)
{
m.AddDelegate(FakeSum);
}
public int FakeSum(int a, int b)
{
return a - b;
}
}
public class Class2
{
public Class2(EvManager m)
{
m.AddDelegate(RealSum);
}
public int RealSum(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
var manager = new EvManager();
var class1 = new Class1(manager);
var class2 = new Class2(manager);
manager.ExecuteIt(5, 12);
}
}
}
Output:
FakeSum(5, 12) = -7
RealSum(5, 12) = 17
You can get the MethodInfoof each one of your split up delegates through the Method Property of the Delegate which has Name property.
class EvManager {
private SumDelegate sum;
public void ExecuteIt(int a, int b) {
var invocationList = sum.GetInvocationList();
foreach (var m in invocationList) {
var concreteMethodName = m.Method.Name;
}
}
}