I have never programmed in C# in my life but i understand java well enough. I am running this program and everytime it keeps saying count/IEnumerator has not been implemented. I have tried various different ways and have put it in various different locations in file. I understand that this will be an extremely easy thing to do but I don't understand it. I also presume these are some sort of methods so don't ask why they are sitting where the instance variables are.
Can someone explain to me how to use collections? The collection being used here is ireadonlycollection which is implemented by IPackOfCards that is implemented in this class.
Are C# interfaces allowed to have implementation in them?
using System;
using CodedTests.NUnit;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace CodedTests.NUnit
{
public class PackOfCards : IPackOfCards
{
private const int NUMCARDS = 52;
private int cardsInPack;
//private Card[] cards;
private Collection<ICard> pack = new Collection<ICard>();
int Count { get; }
public IEnumerator<ICard> GetEnumerator(){return pack.GetEnumerator();}
//IEnumerator IEnumerable.GetEnumerator(){ return GetEnumerator();}
public Collection<ICard> Create()
{
cards = new Card [NUMCARDS];
String [] values = {"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
String [] suits = {"Hearts", "Diamonds", "Spades", "Clubs"};
int cardsInPack = 0;
for(int i = 0 ; i<suits.Length; i++){
for(int j = 0; j<values.Length; j++, cardsInPack++){
cards[cardsInPack]= new Card(values[j], suits[i]);
}
}
return new pack;
}
public void Shuffle(){
Random num = new Random();
for(int i = 0; i<NUMCARDS;i++){
int ran = num.Next(NUMCARDS);
Card temp = cards[ran];
cards[ran] = cards[i];
cards[i] = temp;
}
}
public ICard TakeCardFromTopOfPack (){
int topCard = 0;
ICard cardRemoved = cards[topCard];
for(int i = 0;i<NUMCARDS-1;i++){
cards[i]=cards[i+1];
}
cards[cardsInPack] = null;
cardsInPack--;
return cardRemoved;
}
}
}
public class Card : ICard
{
private String value;
private String suit;
public Card(String v, String s)
{
value = v;
suit = s;
}
public String getValue(){
return value;
}
public String getSuit(){
return suit;
}
public String toString(){
return value+" of "+suit;
}
}
}
public interface IPackOfCards : IReadOnlyCollection<ICard>
{
void Shuffle ();
ICard TakeCardFromTopOfPack ();
}
public interface IPackOfCardsCreator
{
IPackOfCards Create ();
}
public class PackOfCardsCreator : IPackOfCardsCreator
{
public IPackOfCards Create()
IPackOfCards implements IReadOnlyCollection. That means you have to implement all members of IReadOnlyCollection in addition to members of IPackOfCards, namely a Count property and a GetEnumerator method, as documented here. All interface members have to be public, but your Count property is private. You didn't specify its accessibility, so it's defaulted to private.
Related
I am using Google.OrTools version 7.0.
I have built a small interface in order to add constraints to a CpModel:
public interface ISatConstraintWrapper
{
IEnumerable<BoundIntegerExpression> GenerateConstraints();
void BindToModel(CpModel model);
}
The design pattern is fairly simple, here is a dummy example that sets equality to all IntVars in a list:
class MakeAllVarsEqual : ISatConstraintWrapper
{
public MakeAllVarsEqual(List<IntVar> vars)
{
_vars = vars;
}
public IEnumerable<BoundIntegerExpression> GenerateConstraints()
{
for (var i = 0; i < _vars.Count - 1; i++)
{
yield return _vars[i] == _vars[i+1];
}
}
public void BindToModel(CpModel model)
{
foreach (var constraint in GenerateConstraints())
{
model.Add(constraint);
}
}
private readonly List<IntVar> _vars;
}
Next, I would like to use my ISatConstraintWrapper but for minimize/maximize constraints.
Here is an example of what I aim to do:
class MinimizeIntExpression : ISatConstraintWrapper
{
public MinimizeIntExpression(List<IntVar> vars, List<int> coeffs)
{
_vars = vars;
_coeffs = coeffs;
}
public IEnumerable<BoundIntegerExpression> GenerateConstraints()
{
for (var i = 0; i < _vars.Count; i++)
{
yield return _vars[i]*_coeffs[i];
}
}
public void BindToModel(CpModel model)
{
model.Minimize(new SumArray(GenerateConstraints()));
}
private readonly List<IntVar> _vars;
private readonly List<int> _coeffs;
}
But I can't, since _vars[i]*_coeffs[i] returns an IntegerExpression but not a BoundIntegerExpression.
However, even if the latter represents an IntegerExpression in a domain, those two classes seems unrelated and I didn't find a way to downcast a BoundIntegerExpression to an IntegerExpression.
Of course I could make two different interfaces but it wouldn't come as handy, for instance if I want to store my constraint wrappers in a list.
Is it possible to convert a BoundIntegerExpression to an IntegerExpression? If not, how could I modify my wrapper to handle both types of constraints?
You cannot.
I suggest you read:
https://github.com/google/or-tools/blob/stable/ortools/sat/doc/channeling.md
I want to create a global accessible struct/class (in C#) to access my stock prices from the callback handler.
I know only C and it's easy there
Example in C
struct _Sample
{
int SomeValue;
};
struct _Sample Sample[10];
That's what I have so far in C# after 2 hours of trying.
public static class GlobalVar
{
private static double _StockPrice;
public static double SetStockPrice
{
set
{
_StockPrice = value;
}
}
public static double GetStockPrice
{
get
{
return _StockPrice;
}
}
}
The above example can be used as GlobalVar.SetStockPrice = 10.254; I know I have to use the <List> to make _StockPrice available as an array, but all my attempts to compile a working solution failed.
I would like to access it as GlobalVar[1].SetStockPrice = 1.0; and GlobalVar[1].SetStockPrice = 1.0;
I have to use C# because the SDK I'm using is only available in C#.
You would have to add a StockPrice class and keep an internal dictionary inside of GlobalVar to make this work, but you could use this:
public StockPrice this[int index]
{
get
{
StockPrice stockPrice = null;
if (index > -1)
{
InternalDictionary.TryGetValue(index, out stockPrice);
}
return stockPrice;
}
}
Then you can do GlobalVar[index] to get a certain StockPrice object from that internal dictionary of GlobalVar.
Also note that this will not work on a static class because static indexers are not allowed in C#. You might want to change your class to be a singleton instead of a static.
EDIT: A more complete example (still needs work though) with a singleton implementation:
public class GlobalVars
{
static StockPrices _stockPrices = new StockPrices();
public static StockPrices StockPrices
{
get
{
return _stockPrices ;
}
}
}
public class StockPrices
{
Dictionary<int, StockPrice> InternalDictionary = new Dictionary<int, StockPrice>();
public StockPrice this[int index]
{
get
{
StockPrice stockPrice = null;
if (index > -1)
{
InternalDictionary.TryGetValue(index, out stockPrice);
}
return stockPrice;
}
}
public void Add(StockPrice stockPrice)
{
int index = InternalDictionary.Keys.Max() + 1;
InternalDictionary.Add(index, stockPrice);
}
}
Then you could call your code like this:
GlobalVars.StockPrices[1].DoSomething
The C example you gave, is creating an array with 10 instances of the struct.
The equivalent C# code is this:
struct _Sample
{
public int SomeValue;
public static _Sample[] Sample = new _Sample[10];
};
That is not very C#-ish however. Using C# style I would write something like
struct Sample
{
public int SomeValue { get; set; }
public static Sample[] Values = new Sample[10];
}
You can do something like this to have the same behaviour like in c. Notice that you don't need to make SetField and GetField using { get; set; } you get this behaviour by default (it's a property).
public struct Sample
{
public double StockPrice { get; set; }
}
public static class GlobalVar
{
public static Sample[] Samples = new Sample[10];
}
And to acces use
GlobalVar.Samples[1].StockPrice = 1.0;
I have the situation below. Is there a simple way to design this so that the data member sample is shared among all instantiations of ChildClass1 and a separate instance of it is shared with all instances of ChildClass2?
abstract class BaseClass{
int sample = 0;
}
class ChildClass1: BaseClass{
}
class ChildClass2: BaseClass{
}
I'm hoping to produce the following
ChildClass1 a = new ChildClass1();
ChildClass1 b = new ChildClass1();
ChildClass2 c = new ChildClass2();
a.sample = 10;
//a.sample = 10, b.sample = 10, c.sample = 0
Maybe this does, what you want:
public abstract class BaseClass
{
public abstract int Sample { get; set; }
}
public class ChildClass1 : BaseClass
{
private static int mSample = 0;
public override int Sample
{
get { return mSample; }
set { mSample = value; }
}
}
public class ChildClass2 : BaseClass
{
private static int mSample = 0;
public override int Sample
{
get { return mSample; }
set { mSample = value; }
}
}
class Program
{
static void Main(string[] args)
{
var a = new ChildClass1();
var b = new ChildClass1();
var c = new ChildClass2();
a.Sample = 10;
Console.WriteLine(a.Sample); // 10
Console.WriteLine(b.Sample); // 10
Console.WriteLine(c.Sample); // 0
}
}
As I said in my comment, I think there is an inherent flaw in your design, but for the sake of providing an answer, you could achieve it like this:
abstract class BaseClass<TDERIVED>
{
private static Dictionary<Type, int> sampleDictionary_ = new Dictionary<Type, int>();
public BaseClass()
{
} // eo ctor
public int Sample
{
get
{
return sampleDictionary_.ContainsKey(typeof(TDERIVED)) ? sampleDictionary_[typeof(TDERIVED)] : 0;
}
set
{
sampleDictionary_[typeof(TDERIVED)] = value;
}
}
}
class ChildClass1 : BaseClass<ChildClass1>
{
}
class ChildClass2 : BaseClass<ChildClass2>
{
}
This has the added advantage that if you add any other Child classes, they will get their own version of the response. Note that this is not thread-safe, and so if you do choose this solution and want to use it in a multi-threaded environment, you might want to put some thread-safety code in place.
You may want to look into the singleton pattern.
Create a class as a singleton to hold the shared data. Then have all three classes reference the singleton.
I have a class defined with a generic:
public class GenericDataStore<T>
{
// UnderlyingDataStore is another class that manages a queue, or a linked list
private UnderlyingDataStore<T> dataQueue = new UnderlyingDataStore<T>();
public void addData(T data) { dataQueue.Add(data); }
public T getLastData() { dataQueue.getLastData(); }
}
I then have different derived classes based on this class:
public class ByteDataStore : GenericDataStore<Byte>
{
}
public class DoubleDataStore : GenericDataStore<Double>
{
}
public class PObjDataStore : GenericDataStore<PObj> // PObj is another class declared somewhere
{
}
Then, I have a "Manager" class that looks like:
public class DataManager
{
/* Here, I want to declare a 2 dim array [,] that holds pointers to the
data stores. Depending on some other variables, the array may need
to point to DoubleDataStore, ByteDataStore, etc. The following doesn't work,
since GenericDataStore must be declared with a generic type: */
GenericDataStore [,] ManagedDataStores; // Can not compile
public DataManager() {
for (int i=0; i<numStores; i++) {
for (int j=0; j<numCopies; j++) {
// objType is a utility function that we have that returns a type
if (objType(i,j) == typeof(Byte)) {
ManagedDataStores[i,j] = new ByteDataStore();
} else if (objType(i,j) == typeof(double)) {
ManagedDataStores[i,j] = new DoubleDataStore();
}
}
}
}
void Add(int id, int copyid, Byte data) {
ManagedDataStores[i,j].Add(data);
}
}
There might be other, better ways to do this. Essentially, we want to have different data stores for different object types, which can be managed by a class. We want only this 'manager' class to be exposed to the user (like an API), and no direct access to the underlying classes.
Thanks in advance.
I'm afraid that this is one of those instances where Generic's don't help you one bit. By definition, you must know the generic type at compile time, rather than runtime. For runtime type-indiference, you need to do it the old-fashioned way.
public class DataStore
{
// UnderlyingDataStore is another class that manages a queue, or a linked list
private UnderlyingDataStore dataQueue = new UnderlyingDataStore();
public void addData(object data) { dataQueue.Add(data); }
public object getLastData() { dataQueue.getLastData(); }
}
This, has the obvious drawback of boxing/unboxing- as well as the need for calling-code to know what type's it should be dealing with in order to cast.
However, you could also use the other answer, as long as you're able to cast the managedDataStore to the correct generic type.
If you want to create and initialize the double dimensional array use this:
int numStores = 2;
int numCopies = 3;
//GenericDataStore<object>[,] managedDataStores = new GenericDataStore<object>[numStores,numCopies];
Object[,] managedDataStores = new Object[numStores,numCopies];
for (int i = 0; i < numStores; i++)
{
for (int j = 0; j < numCopies; j++)
{
managedDataStores[i,j] = new GenericDataStore<object>();
}
}
I would add an interface and implement it explicitly to hide it from the class users:
internal interface GeneralDataStore
{
void addData(object data);
object getLastData();
}
public class GenericDataStore<T> : GeneralDataStore
{
// UnderlyingDataStore is another class that manages a queue, or a linked list
private UnderlyingDataStore<T> dataQueue = new UnderlyingDataStore<T>();
public void addData(T data) { dataQueue.Add(data); }
public T getLastData() { dataQueue.getLastData(); }
object GeneralDataStore.getLastData() { return getLastData(); }
void GeneralDataStore.addData(object data) { add((T)data); }
}
GeneralDataStore [,] ManagedDataStores;
This doesn't give you what you want, since it's impossible. But it give you some type safety.
I have two constructors which feed values to readonly fields.
public class Sample
{
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}
public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;
private readonly int _intField;
}
One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.
Now here's the catch:
I don't want to duplicate the
setting code. In this case, just one
field is set but of course there may
well be more than one.
To make the fields readonly, I need
to set them from the constructor, so
I can't "extract" the shared code to
a utility function.
I don't know how to call one
constructor from another.
Any ideas?
Like this:
public Sample(string str) : this(int.Parse(str)) { }
If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.
public class Sample
{
private readonly int _intField;
public int IntProperty => _intField;
private void setupStuff(ref int intField, int newValue) => intField = newValue;
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
setupStuff(ref _intField,i);
}
public Sample(int theInt) => setupStuff(ref _intField, theInt);
}
Before the body of the constructor, use either:
: base (parameters)
: this (parameters)
Example:
public class People: User
{
public People (int EmpID) : base (EmpID)
{
// Add more statements here.
}
}
I am improving upon supercat's answer. I guess the following can also be done:
class Sample
{
private readonly int _intField;
public int IntProperty
{
get { return _intField; }
}
void setupStuff(ref int intField, int newValue)
{
//Do some stuff here based upon the necessary initialized variables.
intField = newValue;
}
public Sample(string theIntAsString, bool? doStuff = true)
{
//Initialization of some necessary variables.
//==========================================
int i = int.Parse(theIntAsString);
// ................
// .......................
//==========================================
if (!doStuff.HasValue || doStuff.Value == true)
setupStuff(ref _intField,i);
}
public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
{
setupStuff(ref _intField, theInt);
}
}
Here is an example that calls another constructor, then checks on the property it has set.
public SomeClass(int i)
{
I = i;
}
public SomeClass(SomeOtherClass soc)
: this(soc.J)
{
if (I==0)
{
I = DoSomethingHere();
}
}
Yeah, you can call other method before of the call base or this!
public class MyException : Exception
{
public MyException(int number) : base(ConvertToString(number))
{
}
private static string ConvertToString(int number)
{
return number.toString()
}
}
Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.
class BaseClass
{
public BaseClass():this(10)
{
}
public BaseClass(int val)
{
}
}
class Program
{
static void Main(string[] args)
{
new BaseClass();
ReadLine();
}
}
When you inherit a class from a base class, you can invoke the base class constructor by instantiating the derived class
class sample
{
public int x;
public sample(int value)
{
x = value;
}
}
class der : sample
{
public int a;
public int b;
public der(int value1,int value2) : base(50)
{
a = value1;
b = value2;
}
}
class run
{
public static void Main(string[] args)
{
der obj = new der(10,20);
System.Console.WriteLine(obj.x);
System.Console.WriteLine(obj.a);
System.Console.WriteLine(obj.b);
}
}
Output of the sample program is
50 10 20
You can also use this keyword to invoke a constructor from another constructor
class sample
{
public int x;
public sample(int value)
{
x = value;
}
public sample(sample obj) : this(obj.x)
{
}
}
class run
{
public static void Main(string[] args)
{
sample s = new sample(20);
sample ss = new sample(s);
System.Console.WriteLine(ss.x);
}
}
The output of this sample program is
20
Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:
public class Sample
{
public Sample(object inputToInt)
{
_intField = objectToInt(inputToInt);
}
public int IntProperty => _intField;
private readonly int _intField;
}
public static int objectToInt(object inputToInt)
{
switch (inputToInt)
{
case int inputInt:
return inputInt;
break;
case string inputString:
if (!int.TryParse(inputString, out int parsedInt))
{
throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
}
return parsedInt;
default:
throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
break;
}
}
Please, please, and pretty please do not try this at home, or work, or anywhere really.
This is a way solve to a very very specific problem, and I hope you will not have that.
I'm posting this since it is technically an answer, and another perspective to look at it.
I repeat, do not use it under any condition. Code is to run with LINQPad.
void Main()
{
(new A(1)).Dump();
(new B(2, -1)).Dump();
var b2 = new B(2, -1);
b2.Increment();
b2.Dump();
}
class A
{
public readonly int I = 0;
public A(int i)
{
I = i;
}
}
class B: A
{
public int J;
public B(int i, int j): base(i)
{
J = j;
}
public B(int i, bool wtf): base(i)
{
}
public void Increment()
{
int i = I + 1;
var t = typeof(B).BaseType;
var ctor = t.GetConstructors().First();
ctor.Invoke(this, new object[] { i });
}
}
Since constructor is a method, you can call it with reflection. Now you either think with portals, or visualize a picture of a can of worms. sorry about this.
In my case, I had a main constructor that used an OracleDataReader as an argument, but I wanted to use different query to create the instance:
I had this code:
public Subscriber(OracleDataReader contractReader)
{
this.contract = Convert.ToString(contractReader["contract"]);
this.customerGroup = Convert.ToString(contractReader["customerGroup"]);
this.subGroup = Convert.ToString(contractReader["customerSubGroup"]);
this.pricingPlan= Convert.ToString(contractReader["pricingPlan"]);
this.items = new Dictionary<string, Member>();
this.status = 0;
}
So I created the following constructor:
public Subscriber(string contract, string customerGroup) : this(getSubReader(contract, customerGroup))
{ }
and this method:
private static OracleDataReader getSubReader(string contract, string customerGroup)
{
cmdSubscriber.Parameters[":contract"].Value = contract + "%";
cmdSubscriber.Parameters[":customerGroup"].Value = customerGroup+ "%";
return cmdSubscriber.ExecuteReader();
}
notes: a statically defined cmdSubscriber is defined elsewhere in the code; My main constructor has been simplified for this illustration.
In case you need to run something before calling another constructor not after.
public class Sample
{
static int preprocess(string theIntAsString)
{
return preprocess(int.Parse(theIntAsString));
}
static int preprocess(int theIntNeedRounding)
{
return theIntNeedRounding/100;
}
public Sample(string theIntAsString)
{
_intField = preprocess(theIntAsString)
}
public Sample(int theIntNeedRounding)
{
_intField = preprocess(theIntNeedRounding)
}
public int IntProperty => _intField;
private readonly int _intField;
}
And ValueTuple can be very helpful if you need to set more than one field.
NOTE: most of the solutions above does not work for structs.
Unfortunately initializing struct fields in a method called by a constructor is not recognized by the compiler and will lead to 2 errors:
in the constructor: Field xxxx must be fully assigned...
in the method, if you have readonly fields: a read-only field cannot be assigned except in a constructor.
These can be really frustrating for example when you just need to do simple check to decide on which constructor to orient your call to.