How to reset delegate to original code - c#

given this delegate
public class XYZ
{
public static Action<Profile> DoSomething = (profile) =>
{
//some default code here
return;
};
}
at some time in my main execution I override it with this:
XYZ.DoSomething = (currProfile) =>
{
// some overriding code here
}
How do I set the code back to the original default code when I need to without duplicating code?

Here's a good reason to never use public fields...
Once you set it; its gone. You can hold onto the original value though:
var originalAction = XYZ.DoSomething;
XYZ.DoSomething = ...;
XYZ.DoSomething = originalAction;
Usually it is a bad idea to rely on client code to handle this however; so if I was writing it I would expose as a property like so:
public Action<X> DoSomethingOverride {get; set;}
public Action<X> DoSomething => doSomethingOverride ?? DefaultMethod;
private void DefaultMethod (X param)
{
}
There are a number of other ways to handle this, but all involve storing off the original method. All good ways to handle this will use a property to ensure that only the declaring class is actually setting the DoSomething method and that resetting to the default is possible.
Total aside; since this is static setting the action will affect everything that uses this class. This is asking for bugs later; don't do that.

Maybe somthing like this?
public static Action<Profile> _doSomethingBase = (profile) =>
{
//some default code here
return;
};
public static Action<Profile> _doSomething = _doSomethingBase;
public static Action<Profile> DoSomething
{
get => _doSomething;
set => _doSomething = value;
}
public static void RevertDoSomething()
{
DoSomething = _doSomethingBase;
}

Related

What is the difference between returning a value inside a get, and assigning the property?

If I wanted to keep this handy for non async methods that return task.
public static Task CompletedTaskA { get { return Task.CompletedTask; } }
public static Task CompletedTaskB { get; } = Task.CompletedTask;
Should one be preferred over the other for any kind of context? Or are they the same? I also wonder the same with strings and basically anything i do with properties ie:
get {return "some string"; } vs { get; } = "some string";
EDIT: I would like to clarify my usage of the above prop. I have several event handlers which have Task as a return type, offered to me by a library i'm using. an example of one such event:
private Task Client_MessageReceived(Message message)
{
Task.Run(async ()=> await HandleMessageReceived(message));
// here is where i would use it
return CompletedTask; // A OR B?
}
private async Task HandleMessageReceived(Message message)
{
// Do stuff with message that might take long and block the handler
}
My intention is to save a completed task in a field (i'm choosing a readonly property in this case) and just keep using it to satisfy the task return. I am wondering if one of the above examples, keeps using the same completed task, and the other one keeps asking for another completed task every time?
If you go to SharpLab and look at the code for:
public class C
{
public void M()
{
}
public string Greetig_1
{
get{return "hello";}
}
public string Greeting_2{get;} = "hello";
}
You can see that Greeting_2 is backed by a member variable:
public class C
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly string <Greeting_2>k__BackingField = "hello";
public string Greeting_1
{
get
{
return "hello";
}
}
public string Greeting_2
{
[CompilerGenerated]
get
{
return <Greeting_2>k__BackingField;
}
}
public void M()
{
}
}
This follows through to the IL level. As Greeting_2 is backed by a member variable that variable is initialized in the constructor.
In your example with Task.CompletedTask what you end up with is:
public static Task CompletedTaskB { get; } = Task.CompletedTask;
Caching the Task, whereas:
public static Task CompletedTaskA { get { return Task.CompletedTask; } }
Make a call to get the CompletedTask object in Task each time. In reality this will be inline by the JIT. The approach also has the advantage of not adding an additional (hidden) member variable to your class, which may be an issue if you've got lots of instances and are concerned about memory usage.
They are not the same.
A properties get method is called every time you access it. By default when you create a property, it will have a hidden field behind it so:
public static Task CompletedTaskB { get; set; }
will actually generate this behind the scenes:
private static Task _completedTaskB;
public static Task CompletedTaskB
{
get {
return _completedTaskB;
}
set {
_completedTaskB = value;
}
}
When you assign the property = Task.CompletedTask, you are setting its initial value which is equivalent to :
_completedTaskB = Task.CompletedTask;
When you then access the property, it will read from the private field.
I notice though that you are defining this as readonly (only a getter not a setter) so you will not be able to assign the variable. Instead you will have to use:
public static Task CompletedTaskA { get { return Task.CompletedTask; } }
This will return Task.CompletedTask all the time.
In general the difference between:
{ get; set; } = "some string";
and
get {return "some string"; }
is that the first is an initial assignment whereas the latter is a method that is called whenever you access the property.
When you assign a value to the property right at the definition, some "magic" happens behind the scenes.
The compiler creates a hidden backing field, and the value is assigned to that backing field in the constructor of the class.
In other words, you can think of the two classes below as working the same way.
class AssignedImplicit {
public string Prop {get;} = "example";
}
class AssignedExplicit {
private readonly string Prop_BackingField;
public AssignedExplicit() {
Prop_BackingField = "example";
}
public string Prop { get { return Prop_BackingField; } }
}
When you just define a get method without assigning, the backing field is not created, and no work is added to the constructor.
This is true for strings, or for any other type.
If you assign a value to the property, the work of constructing/fetching that value is put into the constructor of your class. If you create the value in the get method, then the work is put into the get method.

Using IsValueCreated before accessing LazyLoadObject.Value

I'm working with some C# code that's using .Net 4 Lazy loads and I'm not super familiar with it. I'm trying to figure out if this particular code is useless or not.
Originally the property and code below where in the same class, but now I've moved the code to an external class that no longer has access to the private "lazyRecords" property. I'm wondering what the point of checking "lazyRecords.IsValueCreated" is since the lazyRecords.Value has not been invoked yet, wouldn't it always be false? Or is it checking to see if another thread somehow invoked the Value? Or is it doing this in case of a thread exception that resulted in not loading the object?
Property:
private Lazy<List<Record>> lazyRecords;
public List<Record> Records
{
get
{
return lazyRecords.Value;
}
set
{
lazyRecords = new Lazy<List<Record>>(() => value);
}
}
Code:
public Category LoadCategory(BaseClient client)
{
Category category = new Category();
category.Records = client.RecordClient.GetRecordsByCategoryID(category.ID);
if (lazyRecords.IsValueCreated)
{
category.WorldRecord = category.Records.FirstOrDefault();
}
else
{
category.WorldRecord = client.RecordClient.GetWorldRecord(category.ID);
}
}
The code is pretty useless, yes. To help you understand why, consider this very minimal version of Lazy (the real class has more options and logic to take care of multiple threads, but this is the rough idea):
public class Lazy<T>
{
private readonly Func<T> _creator;
private T _cachedValue;
public Lazy(Func<T> creator) => _creator = creator;
public bool IsValueCreated { get; private set; }
public T Value
{
get
{
if (!IsValueCreated)
{
_cachedValue = _creator();
IsValueCreated = true;
}
return _cachedValue;
}
}
}
The delegate passed to the constructor is called on demand, the first time the Value is requested. In the code you've posted there is no point to this because the delegate simply returns the value passed into the setter.
As to the LoadCategory method, the code you posted is hard to decipher. It directly accesses lazyRecords, implying it's a method of the same class. But then it accesses Records on a different object.

NotifyPropertyChanged not firing event [PostSharp]

I'm new to PostSharp (just got my license) and I've been trying to use it in my app. I have a settings class a following:
[NotifyPropertyChanged]
public class Consts
{
public string test2 {get; set;} = "foobar";
public string test
{
get { return GetValue("test"); }
set { UpdateSetting(nameof(test), value.ToString(CultureInfo.InvariantCulture)); }
}
[Pure]
public static string GetValue(string s) => ConfigurationManager.AppSettings[nameof(s)];
[Pure]
private static void UpdateSetting(string key, string value)
{
var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfg.AppSettings.Settings[key].Value = value;
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
}
Then on my subscriber class:
var cst = new Consts();
Post.Cast<Consts, INotifyPropertyChanged>(cst).PropertyChanged +=
(o, args) => Debug.Write("PropertyChanged fired");
cst.test = "test test"; // Gives no result
cst.test2 = "test test"; // Event firing correctly
The event doesn't fire when I use methods in my getters & setters, although marked pure, but works fine when it's a simple property.
I spent the last day scouring Google for answers, without luck; no thread solves my problem.
What am I missing ?
[NotifyPropertyChanged] aspect detects changes to fields of the class and then fires appropriate events based on detected dependencies (property value depending on that specific field).
In your case this is exactly what test2 property does and why aspect works on that property.
On the other hand test property cannot work automatically. The value of the property depends on ConfigurationManager.AppSettings.Item. First problem is that AppSettings is a static property, i.e. it is not possible to detect changes to it. If assumed that it never changes, then second problem is that NameValueCollection does not implement INotifyPropertyChanged, which means that there is no way of knowing that the value actually changed.
You are not getting any warnings because you have marked both methods as Pure which they are not in usual sense of the word. GetValue uses global mutable state. SetValue changes the global mutable state.
Since there is no way to hook to AppSettings in order to receive changes to the collection, you need to raise changed notification when the property is set. This can be done by calling NotifyPropertyChangedServices.SignalPropertyChanged method. Your code would then look like this:
[NotifyPropertyChanged]
public class Consts
{
public string test2 { get; set; } = "foobar";
public string test
{
get { return GetValue("test"); }
set { UpdateSetting(nameof(test), value.ToString(CultureInfo.InvariantCulture)); }
}
[SafeForDependencyAnalysis]
public string GetValue(string s) => ConfigurationManager.AppSettings[nameof(s)];
private void UpdateSetting(string key, string value)
{
var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfg.AppSettings.Settings[key].Value = value;
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
NotifyPropertyChangedServices.SignalPropertyChanged(this, key);
}
}
Note that if multiple instance of Consts class exist, they will not share changes there is no way to pass that information through ConfigurationManaged.

C# - Good and flexible way to pass value types by reference?

My problem, narrowed down to a simple explaination, is the following:
I have a class which needs to work with a number (without changing it) which is subject to change. This number doesn't necessarily come from another class, and it can be anything.
But I'd like to only "give" it to the class once, instead of constantly having to call update methods or having to create a wrapper (since again, as I said, this should work with any kind of number and having to wrap up everything is kind of unpratical).
Here's some code, hoping it helps:
public class SimpleExample
{
int value;
public SimpleExample(int variableOfWhichINeedAReference)
{
//Of course this won't work, but I'll keep it simple.
value = variableOfWhichINeedAReference;
}
public void DisplayValue()
{
print(value);
}
}
public class RandomClass
{
int myValue = 10;
SimpleExample s = new SimpleExample(myValue);
public void WorkWithValue()
{
myValue++;
}
public void Display()
{
print(foo);
print(bar);
s.DisplayValue();
}
}
Now, the problem seems pretty obvious: If I instantiate a SimpleExample and give it a variable as a parameter, it will get its value rather than a reference to it.
Is there a simple enough way that can avoid me the creation of a wrapper? Thanks.
Make a really simple class:
class Ref<T>
{
public T Value;
public Ref<T>()
{
}
public Ref<T>(T value)
{
this.Value = value;
}
}
Then use it like this:
class A
{
Ref<int> x;
public A(Ref<int> x)
{
this.x = x;
}
public void Increment()
{
x.Value++;
}
}
...
Ref<int> x = new Ref<int>(7);
A a = new A(x);
a.Increment();
Debug.Assert(x.Value == 8);
Note that the Ref<T> class here is a reference to a value - not a reference to a variable. If you want a reference to a variable, use Eric Lippert's solution (as pointed out by Filip).
So what you want is not an int, but rather a way of getting an int at some point in time. There are several ways of doing this, one of which is to have your object accept a Func<int>. Then the code can pass in a method that returns the current value of...whatever, rather than the value at the time SimpleExample is created. Using a lambda to close over a variable makes doing this much easier as well.
public class SimpleExample
{
Func<int> func;
public SimpleExample(Func<int> func)
{
this.func = func;
}
public void DisplayValue()
{
print(func());
}
}
public class RandomClass
{
int myValue = 10;
SimpleExample s;
public RandomClass()
{
s = new SimpleExample(() => myValue);
}
public void WorkWithValue()
{
myValue++;
}
public void Display()
{
print(foo);
print(bar);
s.DisplayValue();
}
}
There is no standard wrapper for the purpose you seek, though a single-element array could be used for that purpose. Alternatively, one could define a simple wrapper type:
public class ExposedValueHolder<T> { public T Value; } // Really simple class, eh?
and then use an ExposedValueHolder<YourStructType> to wrap your object. It's not possible in general to capture something passed as an arbitrary ref parameter, since objects may live indefinitely but byrefs (the things which are actually passed when using ref parameters) may die any time after function they're passed to goes out of scope.

Can AutoFixture execute a delegate at object creation time?

I'm looking to customize the creation-time behavior of AutoFixture such that I can set up some dependent objects after the properties of the fixture have been generated and assigned.
For example, suppose I have a method that customizes a User because its IsDeleted property always has to be false for a certain set of tests:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
public static ObjectBuilder<User> BuildUser(this Fixture f)
{
return f.Build<User>().With(u => u.IsDeleted, false);
}
(I hand an ObjectBuilder back to the test so it can further customize the fixture if necessary.)
What I'd like to do is automatically associate that user with an anonymous collection by its Id at creation time, but I can't do this as-is because Id has not been generated by the time I hand the return value back to the unit test proper. Here's the sort of thing I'm trying to do:
public static ObjectBuilder<User> BuildUserIn(this Fixture f, UserCollection uc)
{
return f.Build<User>()
.With(u => u.IsDeleted, false);
.AfterCreation(u =>
{
var relation = f.Build<UserCollectionMembership>()
.With(ucm => ucm.UserCollectionId, uc.Id)
.With(ucm => ucm.UserId, u.Id)
.CreateAnonymous();
Repository.Install(relation);
}
}
Is something like this possible? Or perhaps there is a better way to accomplish my goal of creating an anonymous object graph?
For the Build method, this isn't possible, and probably never will be, because there are much better options available.
First of all, it should never be necessary to write static helper methods around the Build method. The Build method is for truly one-off initializations where one needs to define property or field values before the fact.
I.e. imagine a class like this:
public class MyClass
{
private string txt;
public string SomeWeirdText
{
get { return this.txt; }
set
{
if (value != "bar")
throw new ArgumentException();
this.txt = value;
}
}
}
In this (contrived) example, a straight fixture.CreateAnonymous<MyClass> is going to throw because it's going to attempt to assign something other than "bar" to the property.
In a one-off scenario, one can use the Build method to escape this problem. One example is simply to set the value explicitly to "bar":
var mc =
fixture.Build<MyClass>().With(x => x.SomeWeirdText, "bar").CreateAnonymous();
However, even easier would be to just omit that property:
var mc =
fixture.Build<MyClass>().Without(x => x.SomeWeirdText).CreateAnonymous();
However, once you start wanting to do this repeatedly, there are better options. AutoFixture has a very sophisticated and customizable engine for defining how things get created.
As a start, one could start by moving the omission of the property into a customization, like this:
fixture.Customize<MyClass>(c => c.Without(x => x.SomeWeirdText));
Now, whenever the fixture creates an instance of MyClass, it's just going to skip that property altogether. You can still assign a value afterwards:
var mc = fixture.CreateAnonymous<MyClass>();
my.SomeWeirdText = "bar";
If you want something more sophisticated, you can implement a custom ISpecimenBuilder. If you want to run some custom code after the instance has been created, you can decorate your own ISpecimenBuilder with a Postprocessor and supply a delegate. That might look something like this:
fixture.Customizations.Add(
new Postprocessor(yourCustomSpecimenBuilder, obj =>
{ */ do something to obj here */ }));
(BTW, are you still on AutoFixture 1.0? IIRC, there hasn't been an ObjectBuilder<T> around since then...)
There's a useful discussion on this topic on the AutoFixture CodePlex site.
I believe my postprocessor Customization linked over there should help you. Example usage:
class AutoControllerDataAttribute : AutoDataAttribute
{
public AutoControllerDataAttribute()
: this( new Fixture() )
{
}
public AutoControllerDataAttribute( IFixture fixture )
: base( fixture )
{
fixture.Customize( new AutoMoqCustomization() );
fixture.Customize( new ApplyControllerContextCustomization() );
}
class ApplyControllerContextCustomization : PostProcessWhereIsACustomization<Controller>
{
public ApplyControllerContextCustomization()
: base( PostProcess )
{
}
static void PostProcess( Controller controller )
{
controller.FakeControllerContext();
// etc. - add stuff you want to happen after the instance has been created

Categories