I have a class declared as follows:
public class Eq
{
public bool Equals(ValI x, ValI y)
{
return nilnul.num.ord.Eq.Singleton.Equals( x , y);
//throw new NotImplementedException();
}
public int GetHashCode(ValI obj)
{
return nilnul.num.ord.Eq.Singleton.GetHashCode(obj);
throw new NotImplementedException();
}
static public Eq Singleton=SingletonByDefault<Eq>.Instance;
}
while the SingletonByDefault looks like:
public class SingletonByDefault<YourClass>
where YourClass:new()
//where YourClass:class
{
static protected YourClass _Instance= new YourClass();
static public YourClass Instance
{
get
{
return _Instance;
}
}
protected SingletonByDefault() {
}
}
In most cases when I access Eq.Singleton members, It's fine.
But on one occasion or another, I got a null reference exception which says Eq.Singleton is null.
when I change the static "Singleton" field of class Eq to follows:
//...
static public Eq Singleton{
get{
return SingletonByDefault<Eq>.Instance;
}
}
//....
The exception is gone - at least for now.
I suspect the error is due to the sequence of static field initialization. For now my understanding is that:
1) Eq.Singleton and SingletonByDefault._Instance is initialized to null.
2) when I access Eq.Singleton, Eq.Singleton is intialized to SingletonByDefault.Instance, but
2.1) since now I'm accessing SingletonByDefault.Instance (which in turn accesses SingletonByDefault._Instance), SingletonByDefault._Instance is initialized to new Eq().
3) Eq.Singleton shall now return the "new-ed Eq()". but
3.1) why it's null?
So my understanding must go wrong some where. Anyone would give me some light?
Microsoft's own System.Lazy<> class provides the singleton pattern you need as follows.
public static class MySingletons
{
private static Lazy<Eq> _eq = new Lazy<Eq>( CreateEq );
private static Eq CreateEq()
{
return new Eq();
}
static public Eq Eq { get{ return _eq.Value; }}
}
// usage
var eq = MySingletons.Eq
Update: Here is a further level of generic wrapping as requested by the questioner. This eliminates some repetitive code where the singleton class supports a basic parameter less constructor.
public static class MySingletons
{
static SingletonByLazy<Eq> _eq = new SingletonByLazy<Eq>();
static public Eq Eq
{
get
{
return _eq.Singlton;
}
}
}
public class SingletonByLazy<T> where T: new()
{
Lazy<T> _singltonWrapped = new Lazy<T>( CreateSingleton );
static T CreateSingleton()
{
return new T();
}
public T Singlton
{
get
{
return _singltonWrapped.Value;
}
}
}
Related
I wrote a function in c# which initially returned a named tuple.
But now, I only need one field of this tuple and I would like to keep the name because it helps me to understand my code.
private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
// do something
return (true, false);
}
This function compile. But It's the following function that I want
private static (bool informationAboutTheExecution) doSomething() {
// do something
return (true);
}
the error messages:
Tuple must containt at least two elements
cannot implcitly convvert type 'bool' to '(informationAboutTheExecution,?)
Has somebody a solution to keep the name of the returned value?
I just want to add another option, althought he out is the easiest workaround and Marc explained already why it's not possible. I would simply create a class for it:
public class ExecutionResult
{
public bool InformationAboutTheExecution { get; set; }
}
private static ExecutionResult DoSomething()
{
// do something
return new ExecutionResult{ InformationAboutTheExecution = true };
}
The class can be extended easily and you could also ensure that it's never null and can be created with factory methods like these for example:
public class SuccessfulExecution: ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult{ InformationAboutTheExecution = true };
}
public class FailedExecution : ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult { InformationAboutTheExecution = false };
}
Now you can write code like this:
private static ExecutionResult DoSomething()
{
// do something
return SuccessfulExecution.Create();
}
and in case of an error(for example) you can add a ErrorMesage property:
private static ExecutionResult DoSomething()
{
try
{
// do something
return SuccessfulExecution.Create();
}
catch(Exception ex)
{
// build your error-message here and log it also
return FailedExecution.Create(errorMessage);
}
}
You cannot, basically. You can return a ValueTuple<bool>, but that doesn't have names. You can't add [return:TupleElementNamesAttribute] manually, as the compiler explicitly does not let you (CS8138). You could just return bool. You can do the following, but it isn't any more helpful than just returning bool:
private static ValueTuple<bool> doSomething()
=> new ValueTuple<bool>(true);
Part of the problem is that ({some expression}) is already a valid expression before value-tuple syntax was introduced, which is why
private static ValueTuple<bool> doSomething()
=> (true);
is not allowed.
If you must name your return, you can do this:
private static void doSomething(out bool information) {
// do something
information = true;
}
then call it with
bool result;
doSomething(out result);
I've started using the pattern of a generic result type as a wrapper object that includes a return value and information about the operation like whether it succeeded. Here's an example:
public class Researcher
{
public Result<string> LearnThing(bool factDesired)
{
// Validate and bail if failure
var validationResult = ValidateIntentions(factDesired);
if (!validationResult.Succeeded)
{
// Ideally: return validationResult directly without converting to new instance
return Result.Failure<string>(validationResult.Error);
}
return StateOpinion();
}
public Result<string> StateOpinion()
{
return Result.Success("I like turtles");
}
public Result<bool> ValidateIntentions(bool factDesired)
{
if (factDesired)
{
// Ideally: no <bool> required, infer default instead
return Result.Failure<bool>("Only opinions here, sorry");
}
else
{
return Result.Success(true);
}
}
}
public class Result<T>
{
public bool Succeeded { get; set; }
public string Error { get; set; }
public T Value { get; set; }
}
// Static helpers
public static class Result
{
public static Result<T> Success<T>(T value)
{
return new Result<T> { Succeeded = true, Value = value };
}
public static Result<T> Failure<T>(string error)
{
return new Result<T> { Succeeded = false, Error = error };
}
}
Here, the generic Result<T> class is used on each method and a static helper class provides a mechanism to create the results with success status implied. So far, this is working nicely.
The one bikeshedding annoyance I have with this approach is that I need to restate the <T> often where ideally it could be inferred or when I no longer care about T Value (which would be default) and only about Error, as in the case of failures. I somewhat understand that C# doesn't infer from method return types, but I have come across some mentions of implicit operators that seem to allow some cool tricks that I don't quite understand.
So, I humbly submit the question to the C# wizards among you: is there some variation or magic I can add to this approach to achieve more type inference and effectively an implicit Result<"I don't care"> for failure results?
You can use exactly the same technique as described in the article you linked to.
Step 1: You define a non-generic helper class for your Failure case:
public class FailureResult
{
public string Error { get; }
public FailureResult(string error) { Error = error; }
}
Step 2: You change your static helper to return a FailureResult instead of a Result<T>:
public static class Result
{
...
public static FailureResult Failure(string error)
{
return new FailureResult(error);
}
}
Step 3: You define an implicit conversion from FailureResult to Result<T>:
public class Result<T>
{
...
public static implicit operator Result<T>(FailureResult result)
{
return new Result<T> { Succeeded = false, Error = result.Error };
}
}
Step 4: Profit
public Result<bool> ValidateIntentions(bool factDesired)
{
if (factDesired)
{
// No <bool> required!
return Result.Failure("Only opinions here, sorry");
}
else
{
return Result.Success(true);
}
}
(fiddle)
You could get around the bool issue with just an overload:
public static Result<bool> Failure(string error)
{
return new Result<bool> { Succeeded = false, Error = error };
}
Allowing this:
return Result.Failure("Only opinions here, sorry");
As for:
// Ideally: return validationResult directly without converting to new instance
return Result.Failure<string>(validationResult.Error);
You could use an implicit operator:
public static implicit operator Result<string>(Result<T> result)
{
return Result.Failure<string>(result.Error);
}
Which would allow you to do:
if (!validationResult.Succeeded)
{
// Ideally: return validationResult directly without converting to new instance
return validationResult;
}
Though I personally wouldn't do this, it's unexpected and misusing the language feature.
You could however use an instance method or extension method:
public Result<string> AsError()
{
return Result.Failure<string>(Error);
}
In all honesty, I think what you have is declarative and not trying to be magic. I would just stick with some helper (extension) methods if need be.
Maybe something like this:
public class Result<T>
{
public bool Succeeded { get; set; }
public string Error { get; set; }
public T Value { get; set; }
public bool HasValue { get; protected set; } = true;
}
public class Result : Result<object>
{
public Result() { HasValue = false; }
}
public static class ResultFactory
{
public static Result<T> Success<T>(T value)
{
return new Result<T> { Succeeded = true, Value = value };
}
public static Result Success()
{
return new Result { Succeeded = true };
}
public static Result Failure(string error)
{
return new Result { Succeeded = false, Error = error };
}
}
This allows you not to have to "kludge" in a bool somewhere to to make it fit your pattern. Sure you are creating a null object, but that is more-or-less tucked away.
Assume I have some class that represents a container. That container holds some public properties with get and set modifiers.
What I want is to implement some mechanism that will enable access and disable access to these properties reference at runtime.
For example, when some boolean flag is true, you can access these properties. That means that:
SomeClass.Property1;
Will not generate an exception and will return the object.
However, when it is false, the above line of code will throw an exception.
It is of course possible to be done when using some boolean key, and checking it at the gateway to every property.
My question is, is it possible to implement such mechanism that will enfoce these limitations for all the properties in the class, without the need to assert these conditions within every access to these properties.
Thanks for helping.
It looks like null object pattern might helps.
Simple code that shows how it can be used in your case. Not exactly the same as you want but it doesn't need to assert conditions with every access to object's properties and methods.
Entities:
abstract class AbstractEntity
{
public abstract void DoSomething();
public abstract void DoSomethingElse();
public abstract int Property { get; set; }
}
class RealEntity : AbstractEntity
{
public override void DoSomething()
{
Console.WriteLine("Something");
}
public override void DoSomethingElse()
{
Console.WriteLine("Something else");
}
public override int Property { get; set; }
}
class NullEntity : AbstractEntity
{
public override void DoSomething()
{
// do nothing or throw exception
}
public override void DoSomethingElse()
{
// do nothing or throw exception
}
public override int Property
{
get { throw new Exception(); }
set { throw new Exception(); }
}
}
Simple example of AccessContainer:
class AccessContainer
{
private RealEntity _entity = new RealEntity();
private NullEntity _nullEntity = new NullEntity();
private bool _access = true;
public AbstractEntity Entity
{
get => _access ? (AbstractEntity) _entity : (AbstractEntity) _nullEntity;
}
public void OpenAccess()
{
_access = true;
}
public void DenyAccess()
{
_access = false;
}
}
Usage:
var container = new AccessContainer();
container.Entity.DoSomething(); // prints something
var prop = container.Entity.Property; // access to property
container.DenyAccess();
container.Entity.DoSomething(); // do nothing
container.OpenAccess();
container.Entity.DoSomething(); // prints something again
container.DenyAccess();
var prop2 = container.Entity.Property; // exception
What you are asking for doesn't natively exist, you're going to have to write some sort of wrapping functionality to test whether accessibility is granted.
public interface IAccessOwner {
bool Accessible { get; }
}
[DebuggerDisplay("Accessible: {Accessible,nq} - Value: {ToString()}")]
[DebuggerTypeProxy(typeof(RestrictedObject<>.DebuggerProxy))]
public class RestrictedObject<T> {
private readonly IAccessOwner _owner;
private T _value;
public RestrictedObject(IAccessOwner owner, T initialValue)
: this(owner) {
_value = initialValue;
}
public RestrictedObject(IAccessOwner owner) {
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
}
public T Value {
get {
ThrowIfInaccessible();
return _value;
}
set {
ThrowIfInaccessible();
_value = value;
}
}
public bool Accessible => _owner.Accessible;
public override string ToString() {
if (!Accessible)
return "<Inaccessible>"; // ToString should never throw
if (_value is { } val)
return val.ToString();
return "<null>";
}
private void ThrowIfInaccessible() {
if(!Accessible)
throw new InvalidOperationException("Not accessible!");
}
// explicit operator to cast directly to value
public static explicit operator T(RestrictedObject<T> ro) {
ro.ThrowIfInaccessible();
return ro.Value;
}
private sealed class DebuggerProxy {
public bool Accessible { get; }
public T Value { get; }
public DebuggerProxy(RestrictedObject<T> ro) {
bool acc = Accessible = ro.Accessible;
if (acc)
Value = ro._value;
}
}
}
You can then use properties of this type in your class:
public class MyClass : IAccessOwner {
private readonly RestrictedObject<int> _prop1;
private readonly RestrictedObject<string> _prop2;
public MyClass(int someVal) {
_prop1 = new RestrictedObject<int>(this, someVal);
_prop2 = new RestrictedObject<string>(this);
Accessible = true;
}
public bool Accessible { get; private set; }
// you determine how you want to toggle the above property.
// Exposing it publicly defeats the purpose of all of this,
// but for demo purposes only:
public void DenyAccess() {
Accessible = false;
}
public void AllowAccess() {
Accessible = true;
}
// these properties will throw exceptions if the owner
// (this object) is not currently accessible.
public int Prop1 {
get => _prop1.Value;
set => _prop1.Value = value;
}
public string Prop2 {
get => _prop2.Value;
set => _prop2.Value = value;
}
// alternatively return the wrapper itself
// allowing you to control the accessibility
// even after returning the object
public RestrictedObject<string> AltProp2 => _prop2;
}
You would then use it like the following (obviously exceptions will halt the execution, handling has been elided):
var mc = new MyClass(3);
Console.WriteLine(mc.Prop1); // prints 3
Console.WriteLine(mc.Prop2); // prints null
var temp = mc.AltProp2; // use the wrapper directly
mc.Prop2 = "Hello";
Console.WriteLine(mc.Prop2); // prints Hello
Console.WriteLine(temp.Value); // prints Hello
Console.WriteLine((string)temp); // explicit operator, prints Hello
mc.DenyAccess();
mc.Prop1 = 33; // throws!
Console.WriteLine(mc.Prop1); // throws!
Console.WriteLine(mc.Prop2); // throws!
Console.WriteLine(temp.Value); // throws!
Console.WriteLine((string)temp); // explicit operator, throws!
Console.WriteLine(temp); // prints "<Inaccessible>"
mc.AllowAccess();
string temp3 = (string)temp; // "Hello", explicit operator works again
mc.Prop1 = 22; // as do our setters
mc.Prop2 = "Goodbye";
if (temp.Accessible) {
Console.WriteLine(temp); // "Goodbye"
}
The only thing that won't throw an exception is the override of ToString on the RestrictedObject type itself since you should never throw from ToString. Instead we just return <Inaccessible>.
We've also changed how the RestrictedObject<T> is displayed in a debugger via the DebuggerTypeProxyAttribute. If someone tries to inspect the object's properties they will see the Accessible property and only if true will the wrapped object's Value appear. Otherwise, default(T) will be displayed (null for reference types, 0 for integral types and false for bool). Furthermore, through use of the DebuggerDisplayAttribute we've customized the display of the collapsed version of our object such that it shows the Accessible property alongside our customized ToString.
Note that this still has the drawback that if someone retrieves the inner/wrapped object and accessibility has later been denied, they still have the object. There's nothing you are going to be able to do to really guard against that case. You must also realize (and accept) that anyone using reflection could alter or access the state of the object if they really wanted to.
I will also note that this violates normal C# practices, which typically dictate that properties should not throw exceptions. Microsoft's own guidelines say as much, though they use the term "Avoid" rather than "Do Not". The framework itself is guilty of violating this "rule". If you're going to violate the principle of least surprise, at the very least have the courtesy to document this behavior for consumers of your API.
I have interface that defines value and few operations:
public interface IValue<T>
{
T Value { get; }
void InteractionA(IValue<T> target);
void InteractionB(IValue<T> target);
bool Check(IValue<T> target);
}
Then i implement class based on that interface
public class DoubleValue : IValue<double>
{
public double Value { get; private set; }
public bool Check(IValue<double> target)
{
// ...
return false;
}
public void InteractionA(IValue<double> target)
{
// ...
}
public void InteractionB(IValue<double> target)
{
// ...
}
}
Now i want to make universal manipulator that operates on pool of values and uses generics (so i only write it once). Because of the way i want to use this class in the future it cannot be declared static. Moving generic type into methods also doesn't do any good.
The closest i could get is:
public class ValueManipulator<T>
{
public IEnumerable<IValue<T>> Pool { get; private set; }
public ValueManipulator(IEnumerable<IValue<T>> pool)
{
Pool = pool;
}
public void ManipulateA()
{
foreach (int i in Enumerable.Range(0, Pool.Count()))
{
IValue<T> firstValue = Pool.ElementAt(i);
foreach (IValue<T> secondValue in Pool.Skip(i))
{
if (firstValue.Check(secondValue))
firstValue.InteractionA(secondValue);
else
firstValue.InteractionB(secondValue);
}
}
}
public void ManipulateB()
{
// ...
}
}
Main problem with this ValueManipulator class is that i need to know T of IValue used in DoubleValue (in this case double). So it looks like this:
static void Main(string[] args)
{
ValueManipulator<double> doubleManipulator = new ValueManipulator<double>();
doubleManipulator.Manipulate(ProvideDoubles());
}
private static IEnumerable<DoubleValue> ProvideDoubles()
{
yield return new DoubleValue();
yield return new DoubleValue();
yield return new DoubleValue();
}
How do i make ValueManipulator so user does not need to know what type was used in value implementation?
Well, if your ValueManipulator<T> has no state, as appears to be your case according to your code snippets, then simply make the methods generic instead of the class, that way you can leverage type inference.
public class ValueManipulator
{
public void Manipulate<T>(IEnumerable<IValue<T>> pool)
{
foreach (int i in Enumerable.Range(0, pool.Count()))
{
IValue<T> firstValue = pool.ElementAt(i);
foreach (IValue<T> secondValue in pool.Skip(i))
{
if (firstValue.Check(secondValue))
firstValue.InteractionA(secondValue);
else
firstValue.InteractionB(secondValue);
}
}
}
}
Now you can simply do:
ValueManipulator myManipulator = new ValueManipulator();
myManipulator.Manipulate(ProvideDoubles()); //type inference will figure out T is double
If this is a valid solution then consider making ValueManipulator a static class:
ValueManipulator.Manipulate(ProvideDoubles());
P.D. Please follow advice in commentaries and change ValueType to some other name thats less confusing.
UPDATE After your latest edit to your question, where you clearly state that ValueManipulator<T> does have state, the solution seems to be implementing a static factory class:
public static class ValueManipulator
{
public static ValueManipulator<T> Create<T>(IEnumerable<IValue<T>> pool)
=> new ValueManipulator<T>(pool);
}
public class ValueManipulator<T> { ... }
And again you let type inference do its job:
var doubleManipulator = ValueManipulator.Create(ProvideDoubles());
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.