We recently realized we want to replace our all project from double to float while still saving the option to use double sometimes.
The question is: what is the best practice to do it?
We thought aliasing is the right thing to do but we've found global aliasing is not supported in C#.
Here is an example for the aliasing we've done:
#if USE_FLOAT
using mFloatType = System.Single;
using mComplexType = CenterSpace.NMath.Core.FloatComplex;
using mComplexVector = CenterSpace.NMath.Core.FloatComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.FloatComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.FloatHermitianMatrix;
#else
using mFloatType = System.Double;
using mComplexType = CenterSpace.NMath.Core.DoubleComplex;
using mComplexVector = CenterSpace.NMath.Core.DoubleComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.DoubleComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.DoubleHermitianMatrix;
#endif
While USE_FLOAT is a define symbol.
However, putting this piece of code in every file in the project (more than 500 files) seems totally wrong, especially in object oriented programming.
Any ideas how to do this transition?
If it helps, we are using monoedevelop 6.3 with Mono 4.0.
Thanks.
Since you are dealing with sealed types, you could go with a type factory so that #if/#else/#endif block is only in one file.
Just an example, there are a few ways to do this:
using System;
#region USING_FLOAT
#if USE_FLOAT
using mFloatType = System.Single;
using mComplexType = CenterSpace.NMath.Core.FloatComplex;
using mComplexVector = CenterSpace.NMath.Core.FloatComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.FloatComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.FloatHermitianMatrix;
#else
using mFloatType = System.Double;
using mComplexType = CenterSpace.NMath.Core.DoubleComplex;
using mComplexVector = CenterSpace.NMath.Core.DoubleComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.DoubleComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.DoubleHermitianMatrix;
#endif
#endregion
namespace TypeFactory
{
public static class CenterLineFactory
{
public static mFloatType Double { get { return new mFloatType(); } }
public static mComplexType ComplexType { get { return new mComplexType(); } }
~~~ etc ~~~
}
}
Usage:
var aFloat = CenterLineFactory.Double;
var aComplexType = CenterLineFactory.ComplexType;
But due to the fact this is an afterthought on how your double/float choice is made, it would require all 500 of those files need updated anyway on how you are creating these 5 types...
Personally:
I would use Microsoft's CodeFormatter (https://github.com/dotnet/codeformatter) to bulk convert all your files at once and insert your #if USE_FLOAT/#else/#endif block within a #region USING_FLOAT/#endregion.
I normally never use regions, but would for this. This way you could auto-collapse the USING_FLOAT region and remove it from creating a visual code smell.
One approach could be to use composition instead of inheritance and create a SingleOrDouble struct as below which imitates the behavior of Single or Double based on the build symbol.
You will still need to update all 500 files but it will be a simple find all System.Single and replace with SingleOrDouble
#if USE_FLOAT
public struct SingleOrDouble : IComparable
, IComparable<Single>, IEquatable<Single> {
public Single Value;
private SingleOrDouble(float f) {
Value = f;
}
public static implicit operator float(SingleOrDouble s) {
return s.Value;
}
public static implicit operator SingleOrDouble(float f) {
return new SingleOrDouble(f);
}
public int CompareTo(float other) {
return Value.CompareTo(other);
}
public bool Equals(float other) {
return Value.Equals(other);
}
public static bool IsInfinity(float f) {
return Single.IsInfinity(f);
}
#else
public struct SingleOrDouble : IComparable
, IComparable<Double>, IEquatable<Double> {
public Double Value { get; set; }
private SingleOrDouble(double d) {
Value = d;
}
public static implicit operator double(SingleOrDouble d) {
return d.Value;
}
public static implicit operator SingleOrDouble(double d) {
return new SingleOrDouble(d);
}
public int CompareTo(double other) {
return Value.CompareTo(other);
}
public bool Equals(double other) {
return Value.Equals(other);
}
#endif
public int CompareTo(object obj) {
return Value.CompareTo(obj);
}
public TypeCode GetTypeCode() {
return Value.GetTypeCode();
}
public static bool IsInfinity(double d) {
return Double.IsInfinity(d);
}
}
Please note that above class is not complete but you get the idea.
The class variable can be initialised as below
SingleOrDouble s = 100.5;
which is no different from intializing a normal double as below
double d = 100.5;
Hope this helps
Related
Suppose I have a C# class that has multiple properties that all look like this:
private bool _var1Dirty = true;
private Double? _var1;
public Double? Var1
{
get
{
if (_var1Dirty)
{
_var1 = Method_Var1();
_var1Dirty = false;
}
return _var1;
}
}
And the only differences between each of these properties would be:
The type of return var (in this case Double?, but could just as easily be int, string, etc)
The method call - Method_Var1() (Each property would have a different one)
Is there any way I could write this as a custom class?
Something along the lines of:
public class Prop
{
public delegate T Func();
private bool _dirty = true;
private T _val;
public T Val
{
get
{
if (_dirty)
{
_val = Func;
_dirty = false;
}
return _val;
}
}
}
And then I could pass into it the:
Return type T
Method Func
(PS - I know this won't compile / is dead wrong, but I wanted to give an idea of what I'm looking for)
Any help / guidance would be really appreciated.
Thanks!!!
You're close. You can do something along the lines of this:
public class Dirty<T>
{
public Dirty(Func<T> valueFactory)
{
this.valueFactory = valueFactory;
dirty = true;
}
private Func<T> valueFactory;
private bool dirty;
private T value;
public T Value
{
get
{
if (dirty)
{
value = valueFactory();
dirty = false;
}
return value;
}
}
}
And you consume it like this:
Dirty<double?> dirtyDouble = new Dirty<double?>(() => SomethingThatReturnsADouble());
double? value = dirtyDouble.Value;
I'm not sure what the dirty checking actually does, but if you need someone more complicated than a bool you can always turn it into some Func<T> the checks for dirtiness.
Edit:
Given #mikez comment and your answer, you can save yourself the creation of the Dirty<T> class by using the built in Lazy<T>, which also guarantess thread safety:
public class F
{
private Lazy<double?> lazyDouble = new Lazy<double?>(() =>
MethodThatReturnsNullableDouble(), true);
public double? Value
{
get
{
return lazyDouble.Value;
}
}
}
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 would like to be able to present a choice to the user - whether to use 16bit indices (in OpenGL) or 32bit indices. In C++, I'd probably just create an alias for int or short, but I don't seem to have the option in C#. Basically what I'm going for can be summed up in the class below:
using System;
namespace Something
{
public class Conditional
{
public Conditional(Boolean is16Bit)
{
if (is16Bit)
{
SOMETYPE is Int16
}
else
{
SOMETYPE is Int32
}
}
private List<SOMETYPE> _something;
}
}
The aliasing (if it can be done) would be vastly better - I just don't want to force anyone using this code into writing #define statements, is that possible?
Thanks
Seems like you could use a generic for this:
namespace Something
{
public class Conditional<T>
{
private List<T> _something = new List<T>();
private Conditional()
{
// prevents instantiation except through Create method
}
public Conditional<T> Create()
{
// here check if T is int or short
// if it's not, then throw an exception
return new Conditional<T>();
}
}
}
And to create one:
if (is16Bit)
return Conditional<short>.Create();
else
return Conditional<int>.Create();
You can use an interface and a factory, something like this:
public interface IConditional
{
void AddIndex(int i);
}
private class Conditional16 : IConditional
{
List<Int16> _list = new List<Int16>();
public void AddIndex(int i)
{
_list.Add((short)i);
}
}
private class Conditional32 : IConditional
{
List<Int32> _list = new List<Int32>();
public void AddIndex(int i)
{
_list.Add(i);
}
}
public static class ConditionalFactory
{
public static IConditional Create(bool is16Bit)
{
if (is16Bit)
{
return new Conditional16();
}
else
{
return new Conditional32();
}
}
}
Your code (and callers of it) can do everything against IConditional without caring which of the concrete representations it is.
I've been working on some electrical network simulation software (ElecNetKit). In electrical networks, sometimes it's convenient to work with single-phase models, sometimes in three-phase models.
As such, I would like to be able to represent one of the electrical network elements as:
class Bus
{
public Complex Voltage {set; get;} //single phase property
}
but simultaneously in a fashion so that the user can call Bus.Voltage.Phases[x], and expect a Complex for any valid integer x.
The Bus.Voltage property should map to Bus.Voltage.Phases[1] when treated as a Complex.
I've got two questions here:
Is this in violation of any OOP principles? I've got a feeling that it might be.
Is there a convenient way to represent this in C#?
In terms of representation, I've tried:
a class Phased<T> : T, but this is incompatible with the typing system, and
a class Phased<T> with a generic converter to type T, but the converter still needs to be invoked.
I'm aware that I can simply use something like:
public Dictionary<int,Complex> VoltagePhases {private set; get;}
public Complex Voltage {
set {VoltagePhases[1] = value;}
get {return VoltagePhases[1];}
}
but there's a lot of repetition once you start to do this for multiple properties, across multiple classes.
I would propose something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Numerics;
namespace Test
{
class PhaseList
{
private Dictionary<int, Complex> mPhases = new Dictionary<int, Complex>();
public Complex this[int pIndex]
{
get
{
Complex lRet;
mPhases.TryGetValue(pIndex, out lRet);
return lRet;
}
set
{
mPhases.Remove(pIndex);
mPhases.Add(pIndex, value);
}
}
}
class PhasedType
{
private PhaseList mPhases = new PhaseList();
public PhaseList Phases { get { return mPhases; } }
public static implicit operator Complex(PhasedType pSelf)
{
return pSelf.Phases[1];
}
public static implicit operator PhasedType(Complex pValue)
{
PhasedType lRet = new PhasedType();
lRet.Phases[1] = pValue;
return lRet;
}
}
class Bus
{
public PhasedType Voltage { get; set; }
}
class Program
{
static void Main(string[] args)
{
Bus lBus = new Bus();
lBus.Voltage = new Complex(1.0, 1.0);
Complex c = lBus.Voltage;
lBus.Voltage.Phases[1] = c;
c = lBus.Voltage.Phases[1];
}
}
}
Can you do something like this? This will work similar to your solution at the bottom but because of the generic class you are not repeating the code for each property.
class Program
{
static void Main(string[] args)
{
Collection<Complex> complex = new Collection<Complex>();
//TODO: Populate the collection with data
Complex first = complex.First;
Complex another = complex.Items[2];
}
}
public class Complex
{
// implementation
}
public class Collection<T> where T : class
{
public List<T> Items { get; set; }
public T First
{
get
{
return (Items.Count > 0) ? Items[1] : null;
}
set
{
if(Items.Count > 0)
Items[1] = value;
}
}
}
I want to handle Timeblocks, that means a set of two DateTimes which represent for example the presence of employees. Is there already any structure that i can use to search for a block before or after a specific time?
There are many ways i can imagine to express the situation, like i said with two DateTimes for start and end or with a Datetime for start and a TimeSpan. But i want them to be handled in a kind of Collection. So is there anything similar that i can use or do i have to implement it completely on my own?
Thanks
this library is a great thing - may you get inspired
Time Period Library for .NET
The class:
public class TimePeriod
{
public DateTime Oldest { get; set; }
public DateTime Newest { get; set; }
public TimePeriod(DateTime oldest, DateTime newest)
{
Oldest = oldest;
Newest = newest;
}
public bool Contains (DateTime time)
{
return Oldest.CompareTo(time) <= 0 && Newest.CompareTo(time) >= 0;
}
public bool IsAfter(DateTime time)
{
return Newest.CompareTo(time) <= 0;
}
public bool IsBefore(DateTime time)
{
return Oldest.CompareTo(time) >= 0;
}
}
The Test:
class Program
{
static void Main(string[] args)
{
var period = new TimePeriod(
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(1));
var date = DateTime.Now;
var contains = period.Contains(date); // true
var isBefore = period.IsBefore(date); // false
var isAfter = period.IsAfter(date); // false
date = DateTime.Now.AddDays(-10);
contains = period.Contains(date); // false
isBefore = period.IsBefore(date); // true
isAfter = period.IsAfter(date); // false
date = DateTime.Now.AddDays(10);
contains = period.Contains(date); // false
isBefore = period.IsBefore(date); // false
isAfter = period.IsAfter(date); // true
}
}
Now you can use collections and linq with extensions methods and lambda expression to look for time blocks.
This is not built-in. If you want to implement this yourself you probably want to create a struct. This will give you value-type copy semantics. Such a value behaves just like built-in types like int or DateTime. Very intuitive to use.
You may take a look at TimeSpan. Thats a struct to handle a "Timeblock"
I've used a DateSpan structure before. You can extend is a much as one likes, but this will give you a starting point.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace StackOverFlowDateSpan
{
[StructLayout(LayoutKind.Auto)]
[Serializable]
public struct DateSpan : IComparable, IComparable<DateSpan>, IEquatable<DateSpan>
{
public DateSpan(DateTime start, DateTime end)
: this()
{
Start = start;
End = end;
}
#region Properties
public TimeSpan Duration
{
get { return TimeSpan.FromTicks((End - Start).Ticks); }
}
public DateTime End { get; private set; }
public DateTime Start { get; private set; }
#endregion
public int CompareTo(DateSpan other)
{
long otherTicks = other.Duration.Ticks;
long internalTicks = Duration.Ticks;
return internalTicks > otherTicks ? 1 : (internalTicks < otherTicks ? -1 : 0);
}
public bool Equals(DateSpan other)
{
return End.Equals(other.End) && Start.Equals(other.Start);
}
public int CompareTo(object other)
{
if (other == null)
{
return 1;
}
if (!(other is DateSpan))
{
throw new ArgumentNullException("other");
}
return CompareTo((DateSpan)other);
}
public override bool Equals(object other)
{
if (ReferenceEquals(null, other))
{
return false;
}
return other is DateSpan && Equals((DateSpan)other);
}
public override int GetHashCode()
{
unchecked
{
return (End.GetHashCode() * 397) ^ Start.GetHashCode();
}
}
public static bool operator ==(DateSpan left, DateSpan right)
{
return left.Equals(right);
}
public static bool operator !=(DateSpan left, DateSpan right)
{
return !left.Equals(right);
}
private sealed class EndStartEqualityComparer : IEqualityComparer<DateSpan>
{
#region IEqualityComparer<DateSpan> Members
public bool Equals(DateSpan x, DateSpan y)
{
return x.End.Equals(y.End) && x.Start.Equals(y.Start);
}
public int GetHashCode(DateSpan obj)
{
unchecked
{
return (obj.End.GetHashCode() * 397) ^ obj.Start.GetHashCode();
}
}
#endregion
}
private static readonly IEqualityComparer<DateSpan> _endStartComparerInstance = new EndStartEqualityComparer();
public static IEqualityComparer<DateSpan> EndStartComparer
{
get { return _endStartComparerInstance; }
}
}
}
Thanks for the help! I will tae a closer look at the TimePeriod Library and do some experiments with Linq. I already have an approch that implements binary search, so if someones interested you can write me ;)