i got few line of code where configure method is calling and passing just the string value but ConfigureWith function expect delegate. can anyone help me to understand how ConfigureWith() method will work. thanks
MailTemplate
.ConfigureWith(mt => mt.MailBody = "hello world")
.ConfigureWith(mt => mt.MailFrom = "rdingwall#gmail.com")
.DoSomeOtherStuff()
.Build();
The implementation for this would be:
public class MailTemplate
{
// regular auto properties
public string MailFrom { get; set; }
public string MailBody { get; set; }
public MailTemplate ConfigureWith(Action<MailTemplate> func)
{
func(this);
return this;
}
}
As written it seems entirely pointless, you may as well just set the property on the MailTemplate directly.
Typically in a fluent builder like this you would save the Actions being passed in with each ConfigureWith call and then execute them later.
It might help if you explain in more detail what you hope to achieve with the fluent syntax you are creating. As written it also will not compile since the first call expects a static method. Can you show the real code?
You might also want to look at other answers on StackOverflow regarding fluent methods (e.g. Tips for writing fluent interfaces in C# 3)
I see that the example above is from an answer to a different question you asked earlier. I'm still not entirely sure what you're trying to do, and as Ian Mercer suggested, it's pretty pointless as written. But if you're just trying to understand what it does, then let's first get a working example:
using System;
namespace ScratchApp
{
internal class Program
{
private static void Main(string[] args)
{
var mailTemplate = BuildMailTemplate(
mt => mt.MailBody = "hello world",
mt => mt.MailFrom = "rdingwall#gmail.com");
}
private static MailTemplate BuildMailTemplate(
Action<MailTemplate> configAction1,
Action<MailTemplate> configAction2)
{
var mailTemplate = new MailTemplate();
mailTemplate.ConfigureWith(configAction1)
.ConfigureWith(configAction2)
.DoSomeOtherStuff()
.Build();
return mailTemplate;
}
}
public class MailTemplate
{
public string MailFrom { get; set; }
public string MailBody { get; set; }
public MailTemplate DoSomeOtherStuff()
{
// Do something
return this;
}
public MailTemplate Build()
{
// Build something
return this;
}
public MailTemplate ConfigureWith(Action<MailTemplate> func)
{
func(this);
return this;
}
}
}
This is as pointless as before, but it builds. What's happening when you're calling .ConfigureWith() is that instead of passing a normal value, you're passing it a function. In the example above, I'm actually declaring the functions as parameters that get passed into the BuildMailTemplate() method, and which in turn get executed when the template is being built and configured. You can get a feel for how it works by stepping through the code, line-by-line (e.g., F11 in Visual Studio), and setting breakpoints in the lambda expressions themselves, and then looking at the call stack.
If you're confused about the syntax for lambdas - arrow syntax is indeed a bit complex when you're first getting used to it - then feel free to check out the MSDN article on it, or just Google "c# lambdas" to your heart's delight.
Related
I would like to use a function as a variable for me to assign.
Something like this
Class:
public class Func
{
public string Name { get; set; }
public string Content { get; set; }
public Function function { get; set; } //Not sure what type for a func
}
Func:
public void Click_Event(object sender,EventArgs e)
{
//Some code here.
}
List to assign the func:
List<Func> funcList = new List<Func>();
Func func = new Func();
func.Name = "Name";
func.Content = "Hello World";
func.function = Click_Event; //This is what I really want to do.
funcList.Add(func);
Is there anyway to achieve this?
Edited
Some of the comment below said that Reflection may cause the performance issue, but I use it and doesn't seen any slow issue currently. I use it when I first start the app only.
This is the sample code I use it.
MethodInfo method = this.GetType().GetMethod("FuncName"); //Or using nameof
btnFunc.AddHandler(Button.ClickEvent, Delegate.CreateDelegate(Button.ClickEvent.HandlerType, this, method, false));
Try using a delegate:
A delegate is a data structure that refers to a static method or to a
class instance and an instance method of that class.
https://learn.microsoft.com/en-us/dotnet/api/system.delegate?view=netframework-4.8
Another option to look into would be an Action or Func
After a several research, I have found another way to solve this.
Save the function name as a string instead of as a Action or delegate
Then use System.Reflection.MethodInfo and btn.AddHandler to use it.
By this way, the function must be public.
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.
Update: Turns out there were details I had completely missed until I looked at the source code of the library I was using. Apologies for the bad example code starting out, was trying to focus on what I thought was relevant.
Working with FlatFiles NuGet library which has 25 overloads for a Property(...) method. I'm trying to dispatch the correct Property(...) overload from my generic method by using dynamic on a parameter I'm passing, but this isn't working. Here's what I tried:
using FlatFiles;
using FlatFiles.TypeMapping;
public class FixedWidthDataSource<FixedWidthRecordT> {
public IFixedLengthTypeMapper<FixedWidthRecordT> Mapper
= FixedLengthTypeMapper.Define<FixedWidthRecordT>()
;
...
public void MapProperty<T>(
Expression<Func<FixedWidthRecordT, T>> col
, int width
, string inputFormat = null
) {
var window = new Window(width);
Mapper.Property((dynamic)col, window);
}
}
public class FixedWidthRecord
{
public string First { get; set; }
public string Last { get; set; }
}
//later
var fwds = new FixedWidthDataSource<FixedWidthRecord>();
fwds.MapProperty(c=>c.First, 5);
A few of the Property overloads:
Property(Expression<Func<FixedWidthRecordT, bool>> property, Window window);
Property(Expression<Func<FixedWidthRecordT, int>> property, Window window);
Property(Expression<Func<FixedWidthRecordT, string>> property, Window window);
The error I get is 'FlatFiles.TypeMapping.IFixedLengthTypeMapper<FixedWidthRecord>' does not contain a definition for 'Property'.
Looking at the source I see the there's an
internal sealed class FixedLengthTypeMapper<TEntity>
and this is the type of object that's being returned from the call to FixedLengthTypeMapper.Define<FixedWidthRecordT>() and assigned to Mapper. However, IFixedLengthTypeMapper does not have any definitions for Property(...), only FixedLengthTypeMapper has them.
Hoping that's all relevant.
Maybe your case has something to do with this? RuntimeBinderException – “does not contain a definition for”.
That article gets that exception in the case of an anonymous object, but your case seems similar. Your assembly is trying to access something through dynamic it cannot normally see: an internal class in your case, an anonymous type in theirs.
Adding the [assembly: InternalsVisibleTo("Your.Assembly")] attribute on the library doesn't sound like a good option, but if you can build from source it could help temporarily. Or maybe with that info you could create a solid repro.
Here is what I finally did to get it working, although it's by using an interface not described in the library's usage documentation. I'm still curious how this could have otherwise been solved (say for instance, if the IFixedLengthTypeConfiguration interface I'm using in the solution were also defined as internal).
using FlatFiles;
using FlatFiles.TypeMapping;
public class FixedWidthDataSource<FixedWidthRecordT> {
public IFixedLengthTypeConfiguration<FixedWidthRecordT> Configuration
= FixedLengthTypeMapper.Define<FixedWidthRecordT>()
;
public IFixedLengthTypeMapper<FixedWidthRecordT> Mapper;
public FixedWidthDataSource() {
Mapper = (IFixedLengthTypeMapper<FixedWidthRecordT>)Configuration;
}
...
public void MapProperty<T>(
Expression<Func<FixedWidthRecordT, T>> col
, int width
, string inputFormat = null
) {
var window = new Window(width);
Configuration.Property((dynamic)col, window);
}
}
public class FixedWidthRecord
{
public string First { get; set; }
public string Last { get; set; }
}
//later
var fwds = new FixedWidthDataSource<FixedWidthRecord>();
fwds.MapProperty(c=>c.First, 5);
I am thinking to create a filter object which filters and delete everything like html tags from a context. But I want it to be independent which means the design pattern I can apply will help me to add more filters in the future without effecting the current codes. I thought Abstract Factory but it seems it ain't gonna work out the way I want. So maybe builder but it looks same. I don't know I am kinda confused, some one please recommend me a design pattern which can solve my problem but before that let me elaborate the problem a little bit.
Lets say I have a class which has Description field or property what ever. And I need filters which remove the things I want from this Description property. So whenever I apply the filter I can add more filter in underlying tier. So instead of re-touching the Description field, I can easily add more filters and all the filters will run for Description field and delete whatever they are supposed to delete from the Description context.
I hope I could describe my problem. I think some of you ran into the same situation before.
Thanks in advance...
Edit :
I actually want to create filters as types/classes instead of regular methods or whatever. Like :
class TextFilter : IFilter
{
private string something;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class HtmlFilter : IFilter
{
private string something;
private string iGotSomething;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class Main
{
protected void Main(object sender, EventArgs e)
{
InputClass input = new InputClass();
string filtered = new StartFiltering().Filter(input.Description); // at this moment, my input class shouldn't know anything about filters or something. I don't know if it makes any sense but this is what in my mind.
}
}
At this point if I want to apply Abstract Factory which would be meaningless or Builder as well. Because I don't want a particular thing, I need all of them kinda.
Thanks for your answers by the way.
Edit 2 - Possible Answer for Me
Okay lets think about strategy pattern with interfaces rather than delegates.
interface IFilter //Strategy interface
{
string Filter(string text);
}
class LinkFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter link tags and return pure text;
}
}
class PictureFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter links and return pure text;
}
}
class Context
{
private IFilter _filter;
private string _text;
public Context(IFilter filter,string text)
{
this._filter = filter;
this._text = text;
}
public void UpdateFilter(IFilter filter)
{
this._filter = filter;
}
public string RunFilter()
{
this._text = _filter.Filter(this._text);
return this._text;
}
}
class MainProgram
{
static void Main()
{
MyObject obj = new MyObject();
LinkFilter lfilter = new LinkFilter();
PictureFilter pfilter = new PictureFilter();
Context con = new Context(lfilter,obj.Description);
string desc = con.RunFilter();
con.UpdateFilter(pfilter);
desc = con.RunFilter();
}
}
Why don't you just go light weight: Define your filter as a Func<string, string>. If you keep these in a collection (List<Func<string, string>>), you can just do:
var text = myObject.DescriptionProperty
foreach (var func in myFuncList)
{
text = func(text);
}
You can also use Linq to shorten the above loop:
var text = myFuncList.Aggregate(text, (seed, func) => func(seed));
This way, you don't have to define a class hierarchy for filtering. This is good for the environment, since we will be running out of classes and namespaces very soon!
To wrap things up, I suggest you subclass List:
public class FilterCollection : List<Func<string, string>>
{
public string Filter(string text)
{
return this.Aggregate(text, (seed, func) => func(seed));
}
}
Have you looked at the strategy pattern? It allows you to swap algorithms.
If that is not what you are looking for, perhaps the decorator pattern will be more suitable. This will allow you to wrap filters and apply multiple ones if needed.
To me this sounds like the Strategy pattern.
Could be something like this (the code is in VB):
Function GetFilteredDescription(ByVal iSpecificFilterFunction As AbstractFilterFunction) As Result
Return iSpecificFilterFunction.Filter(Me.description)
End Function
Note: the GetFilteredDescription is member function of your class.
You can use below patterns:
Strategy Pattern for different Filter types
Chain of Responsibility for your filter stack (You can add Command Pattern here for different chains in a multitasking environment, or you can implement priority based chain or so on )
Builder or Abstract Factory for Filter instance creations.
What about Provider pattern? http://msdn.microsoft.com/en-us/library/ms972319.aspx
It is similar to Strategy, and is used in Microsoft products thoroughly.
I have some extension methods which could be used like this:
MyType myObject;
string displayName = myObject.GetDisplayName(x => x.Property);
The problem here is that it needs an instance, even if the extension method only needs the type MyType. So if there is no instance, it needs to be called like this:
string displayName = BlahBlahUtility.GetDisplayName((MyTpe x) => x.Property);
Which is not so nice anymore.
Is there a way to write better syntax for such cases?
What I actually want to do is this (pseudo language):
string displayName = MyType.Property.GetDisplayName()
Which of course does not work with C#.
But what about something like this:
string displayName = ((MyType x) => x.Property).GetDisplayName();
This is also not possible (after a lambda, a dot is not accepted).
Any ideas?
Edit:
My "favorite syntax" MyType.Property.GetDisplayName() seems to be misleading. I don't talk about static properties here. I know that this syntax won't be possible. I just tried to show in pseudo language, what information is necessary. This would be ideal, every additional stuff is just syntactical overhead. Any working syntax that is close to this would be great.
I don't want to write a certain extension method. I want an easy, readable and compile time safe syntax, using any language feature.
Have a look at the Express and Reflect classes in the Lokad Shared Libraries. Think they may help out with what you are trying to do. Read more here:
Strongly Typed Reflection in Lokad Shared
How to Find Out Variable or Parameter Name in C#?
From your comment: "I want an easy and compile time safe syntax to get information about members".
This is a very frequently requested feature and has been discussed in the C# team's meetings for about a decade, but has never been prioritised high enough to be included.
This blog post explains why:
http://blogs.msdn.com/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx
So for now, you're just going to be fighting against a missing feature. Maybe you could post more information about your broader problem and see if people can suggest different approaches.
Update
Without more info about your problem this is just guesswork. But if you have a property that represents a value but also carries additional "meta" information, you could always represent that as a new type and use an "injection" step to set everything up.
Here's a suggested abstract interface to such a "meta property":
public interface IMetaProperty<TValue>
{
TValue Value { get; set; }
string DisplayName { get; }
event Action<TValue, TValue> ValueChanged;
}
The value of the property is just another sub-property, with its type defined by the user.
I've put in the display name, and also as a bonus you've got an event that fires when the value changes (so you get "observability" for free).
To have properties like this in a class, you'd declare it like this:
public class SomeClass
{
public IMetaProperty<string> FirstName { get; private set; }
public IMetaProperty<string> LastName { get; private set; }
public IMetaProperty<int> Age { get; private set; }
public SomeClass() { MetaProperty.Inject(this); }
}
Note how the setters on the properties are private. This stops anyone from accidentally setting the property itself instead of setting the Value sub-property.
So this means the class has to set up those properties so they aren't just null. It does this by calling a magic Inject method, which can work on any class:
public static class MetaProperty
{
// Make it convenient for us to fill in the meta information
private interface IMetaPropertyInit
{
string DisplayName { get; set; }
}
// Implementation of a meta-property
private class MetaPropertyImpl<TValue> : IMetaProperty<TValue>,
IMetaPropertyInit
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
var old = _value;
_value = value;
ValueChanged(old, _value);
}
}
public string DisplayName { get; set; }
public event Action<TValue, TValue> ValueChanged = delegate { };
}
public static void Inject(object target)
{
// for each meta property...
foreach (var property in target.GetType().GetProperties()
.Where(p => p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition()
== typeof(IMetaProperty<>)))
{
// construct an implementation with the correct type
var impl = (IMetaPropertyInit)
typeof (MetaPropertyImpl<>).MakeGenericType(
property.PropertyType.GetGenericArguments()
).GetConstructor(Type.EmptyTypes).Invoke(null);
// initialize any meta info (could examine attributes...)
impl.DisplayName = property.Name;
// set the value
property.SetValue(target, impl, null);
}
}
}
It just uses reflection to find all the IMetaProperty slots hiding in the object, and fills them in with an implementation.
So now a user of SomeClass could say:
var sc = new SomeClass
{
FirstName = { Value = "Homer" },
LastName = { Value = "Simpson" },
Age = { Value = 38 },
};
Console.WriteLine(sc.FirstName.DisplayName + " = " + sc.FirstName.Value);
sc.Age.ValueChanged += (from, to) =>
Console.WriteLine("Age changed from " + from + " to " + to);
sc.Age.Value = 39;
// sc.Age = null; compiler would stop this
If you're already using an IOC container you may be able to achieve some of this without going directly to reflection.
It looks like you're trying to create a static extension method?
DateTime yesterday = DateTime.Yesterday(); // Static extension.
Instead of
DateTime yesterday = DateTime.Now.Yesterday(); // Extension on DateTime instance.
If this is what you're trying to pull off, I do not believe it is possible in the current version of C#.
It sounds like you are integrating layers a little too tightly. Normally in this type of situation I would let the presentation layer decide the implementation of GetDisplayName() instead of making it an extension of the property itself. You could create an interface called MyTypeDisplayer or whatever you fancy, and let there be multiple implementations of it not limiting you to a single display implementation.
The issue here is that one cannot get a reference to non-static methods via instance MyType.[Member]. These can only be seen through a reference to an instance of the type. You also cannot build an extension method on-top of a type declaration, only on an instance of a type - that is the extension method itself has to be defined using an instance of a type (this T x).
One can however define the expression like this to get a reference to static members:
((MyType x) => MyType.Property)
One could do something similar to string displayName = ((MyType x) => x.Property).GetDisplayName();
The first issue is guaranteeing that the compiler treats your (x=> x.Property) as an Expression rather than an action/func etc...
To do this one might need to do this:
string displayName = ((Expression<Func<PropertyType>>)((MyType x) => x.Property).GetDisplayName();
The extension method would then have to be defined like this:
public static string GetDisplayName<T>(this Expression<Func<T>> expression)
You might also have to define an extension method on top of Expression<Action>> and Expression<Action<T>> if your members are also methods.
You can do a dot after an Expression - this is where the Compile method would reside.
Appended:
I think the static call to the extension method in cases that one doesn't have an instance of the type one needs to do "reflection" on to determine a Members name would be the cleanest syntax still - this way you could still use the extension method when using an instance of a type and fall back to the static call definition => MyExtensionClass.GetDisplayName(TypeOfX x => TypeOfX.StaticMember OR x.Property/Member) when one doesn't have an instance
If you interface your properties, you could make the extension on the interface instead:
namespace Linq1
{
class Program
{
static void Main(string[] args)
{
MyType o = new MyType();
o.Property.GetDisplayName();
}
}
public class MyType
{
public IDisplayableProperty Property { get; set; }
}
public interface IDisplayableProperty
{
string GetText();
}
public class MyProperty1 : IDisplayableProperty
{
public string GetText() { return "MyProperty2"; }
}
public class MyProperty2 : IDisplayableProperty
{
public string GetText() { return "MyProperty2"; }
}
public static class Extensions
{
public static string GetDisplayName(this IDisplayableProperty o)
{
return o.GetText();
}
}
}