Here is pseudo code of what this would look like if I could modify the class in question
public class Foo
{
private TheDataType _Data;
public TheDataType GetData()
{
if (_Data != null)
return _Data;
// fetch/generate data
return _Data;
}
}
How do I turn this into an extension method? The definition/scope of the _Data is what bothers me...
================================================
This is probably the closest to what I want, but feel like an overkill for something so simple
public static class FooExtensions
{
private static ConcurrentDictionary<Foo,TheDataType> DataCache = new ConcurrentDictionary<Foo,TheDataType>();
public static TheDataType GetData(this Foo foo)
{
TheDataType data;
if (DataCache.TryGetValue(foo, out data))
return data
// fetch/generate data
DataCache.Add(foo, data);
return data;
}
}
You could have your extension method utilize a cache manager class (custom or built into the framework) which kept track of the data based on some unique identifier for the instance:
public static DataType GetData( this Foo obj )
{
DataType retVal;
// this sample doesn't show any locking, i.e. it is not thread safe
// if cache manager contains data return from there
if( CacheManager.HasData( obj.UniqueId ) )
{
retVal = CacheManager.GetData( obj.UniqueId );
}
else
{
// otherwise invoke a method on obj and add to cache
retVal = obj.GetData();
CacheManager.Add( obj.UniqueId, retVal );
}
return retVal;
}
However, this strikes me as a potential misuse of an extension method, even though it's syntactically clean. It would depend on the context in which it is used and on how obvious the side effects were. For example this would be really hard for another developer to troubleshoot if they didn't know that GetData() was using a cache, the cache expiration wasn't clear, etc.
This is a good fit for function caching, described in this blog post of mine. The idea is to take a function with one argument and turn it into another function which caches the result of the original one:
public static Func<TKey, TValue> Cached<TKey, TValue>(this Func<TKey, TValue> valueFunction)
{
var cache = new Dictionary<TKey, TValue>();
return key =>
{
TValue value;
if(!cache.TryGetValue(key, out value))
{
value = valueFunction(key);
cache[key] = value;
}
return value;
};
}
The cache dictionary gets embedded inside the returned closure, so it will have the same lifetime of the function we return.
You would use it by replacing the original call to get the data with the new function:
public class UsesTheDataType
{
private readonly Func<Foo, TheDataType> _generateData;
public UsesTheDataType()
{
_generateData = GenerateData;
_generateData = _generateData.Cached();
}
public void UseTheDataType(Foo foo)
{
var theDataType = _generateData(foo);
// theDataType is either a new value or cached value
}
private TheDataType GenerateData(Foo foo)
{
// Only called the first time for each foo
}
}
The nice part here is that the caching is written once for all functions, so you can reuse the same approach no matter what you have to cache. This also avoids possible memory leaks resulting from the use of a static cache.
This can also be done in a thread-safe manner. See the second post in the series for a walkthrough.
I'm not quite sure what you are trying to accomplish, but if I follow, it would look something like.
public static class FlargExtensions
{
private static Flarg flarg;
public static Flarg GetData(this Flarg flarg)
{
if (FlargExtensions.flarg != null)
return Class1.flarg;
FlargExtensions.flarg = new Flarg();
return FlargExtensions.flarg;
}
}
public class Flarg
{
}
Related
How can I convert these two ConvertDtoListToAddresses and ConvertDtoListToDocuments C# methods to a generic? I've tried passing in two generic type variables, but when I get down to 'Add' in the loop I get stuck on various errors. Converting from a DTO to its respective DBO is done in the constructor of the DBO, which I think is part of the problem.
private void ConvertDtoToPerson(PersonDTO dto)
{
Id = dto.Id;
Fname = dto.FirstName;
Mname = dto.MiddleName;
Lname = dto.LastName;
Suffix = dto.Suffix;
Maiden = dto.MaidenName;
Addresses = ConvertDtoListToAddresses(dto.AddressesDto); // want to convert to generic
Documents = ConvertDtoListToDocuments(dto.DocumentsDto); // want to convert to generic
}
private static ICollection<Address>? ConvertDtoListToAddresses(ICollection<AddressDTO>? addressesDto)
{
if (addressesDto is not null && addressesDto.Any())
{
ICollection<Address> addys = new List<Address>();
foreach (AddressDTO dto in addressesDto)
{
// Converts from dto in constructor
addys.Add(new Address(dto));
}
return addys;
}
return null;
}
private static ICollection<Document>? ConvertDtoListToDocuments(ICollection<DocumentDTO>? documentsDto)
{
if (documentsDto is not null && documentsDto.Any())
{
ICollection<Document> docs = new List<Document>();
foreach (DocumentDTO dto in documentsDto)
{
// Converts from dto in constructor
docs.Add(new Document(dto));
}
return docs;
}
return null;
}
Here is what I tried:
Addresses = ConvertDtoListToType<Address, AddressDTO>(dto.AddressesDto);
private static ICollection<T>? ConvertDtoListToType<T, D>(ICollection<D>? dtoCollection)
{
if (dtoCollection is not null && dtoCollection.Any())
{
ICollection<T> tList = new List<T>();
foreach (D dto in dtoCollection)
{
tList.Add(new T(dto)); // <-- This is where I'm having trouble
}
return tList;
}
return null;
}
Use of a Func<D, T> factory parameter would sort this out.
private static ICollection<T>? ConvertDtoListToType<T, D>(ICollection<D>? dtoCollection, Func<D, T> factory)
{
if (dtoCollection is not null && dtoCollection.Any())
{
ICollection<T> tList = new List<T>();
foreach (D dto in dtoCollection)
{
tList.Add(factory(dto));
}
return tList;
}
return null;
}
Do keep in mind that that is almost the semantic equivalent of this:
private static ICollection<T>? ConvertDtoListToType<T, D>(ICollection<D>? dtoCollection, Func<D, T> factory)
=> dtoCollection?.Select(d => factory(d))?.ToList();
I'd question the idea that an empty dtoCollection should return a null final collection anyway. This is probably a better implementation.
So, having said that, your original method offers very little functionality benefit. It's code for code's sake. A simple Select/ToList pair keeps your code simple.
In any case, you can provide a static method off of Address and Document to provide the Func<D, T> that you need.
public class Address
{
AddressDTO dto;
public static Address CreateFromDto(AddressDTO dto)
=> new Address(dto);
public Address(AddressDTO dto)
{
this.dto = dto;
}
}
Now, calling it is like this:
var addresses = ConvertDtoListToType(addressDtos, Address.CreateFromDto);
Or:
var addresses = addressDtos?.Select(Address.CreateFromDto)?.ToList();
What you need is to be able to provide a constraint on the Type T to say that it has a constructor that takes a parameter of type D. Something like this:
private static ICollection<T>? ConvertDtoListToType<T, D>(
ICollection<D>? dtoCollection) where T : new(D)
{}
But this does not exist in C#. The workaround is to provide a factory method to create your type T given a type D. i.e. Something like:
private static ICollection<T>? ConvertDtoListToType<T, D>(
ICollection<D>? dtoCollection, Func<D, T> factory)
{
// Use factory(dto), instead of new T(dto)
}
But as #Zee says, you should have a look at Automapper, which can convert between types of collections.
I am wondering if there is some way to optimize the using statement to declare and assign its output together (when it is a single value).
For instance, something similar to the new way to inline declare the result variable of an out parameter.
//What I am currently doing:
string myResult;
using(var disposableInstance = new myDisposableType()){
myResult = disposableInstance.GetResult();
}
//That would be ideal
var myResult = using(var disposableInstance = new myDisposableType()){
return disposableInstance.GetResult();
}
//That would be great too
using(var disposableInstance = new myDisposableType(), out var myResult){
myResult = disposableInstance.GetResult();
}
Thanks for your input.
You can use extension method to "simplify" this usage pattern:
public static class Extensions {
public static TResult GetThenDispose<TDisposable, TResult>(
this TDisposable d,
Func<TDisposable, TResult> func)
where TDisposable : IDisposable {
using (d) {
return func(d);
}
}
}
Then you use it like this:
string myResult = new myDisposableType().GetThenDispose(c => c.GetResult());
This is funny, because I started reading Functional Programming in C# a couple of days ago, and one of the first examples is along the lines of:
public static TResult Using<TDisposable, TResult>(TDisposable disposable, Func<TDisposable, TResult> func)
where TDisposable : IDisposable
{
using (disposable)
{
return func(disposable);
}
}
Usage:
var result = Using(new DbConnection(), x => x.GetResult());
Notice that, unlike the other answers posted, this function has absolutely no responsibility but get the result of func, regardless of TDisposable.
No, there is no such shortcut. Your original way is right.
You could wrap this in a function if you do it often enough
public class Utilities
{
public static TReturn GetValueFromUsing<T,TReturn>(Func<T,TReturn> func) where T : IDisposable, new()
{
TReturn result = default(TReturn)
using(var instance = new T())
result = func(instance);
return result;
}
}
usage
var result = Utilities.GetValueFromUsing<myDisposableType,string>(x => x.GetResult());
But man would that be overkill.
The using instruction cannot be used as r-value, and therefore there is no way to assign a value from it.
However, there is a special case to this, and you can use it where convenient: You can return a result from inside the using block.
int F(int arg)
{
using (disposable = GetObj())
{
return disposable.Calculate(arg);
}
}
This form is often communicating the purpose better than a local variable assignment. You can even turn it into a template method, where the method would apply the using construct and then call a strategy and return its result.
class Useful<TDisposable> where TDisposable : IDisposable
{
private Func<TDisposable> Factory { get; }
public Useful(Func<TDisposable> factory)
{
this.Fatory = factory;
}
public TResult SafeDo<TResult>(Func<TDisposable, TResult> operation)
{
using (TDisposable obj = this.Factory())
{
return operation(obj);
}
}
}
This class is completely reusable and its single responsibility is to ensure that disposable components are disposed on use. Instead of working directly with a disposable class, you can wrap it into this wrapper class and consume it that way and you'll have a strict lifetime control over the disposable objects:
void Worker(Useful<MyDisposableClass> wrapper)
{
int arg = 5;
wrapper.SafeDo(disp => disp.Calculate(arg);
}
In this piece of code, the disp object would be constructed and disposed correctly. A concrete argument that would be required by the operation arg is taken from the closure.
Is there something inherently wrong with replacing
IDictionary<int, IEnumerable<string>>
with
ILookup<int, string>
I much prefer ILookup over IDictionary because of its more 'honest' interface and immutability.
However, I discovered that ILookup is unable to hold empty collections, so keys containing empty collections are simply do not exist in it. This is problem, because I also would like ILookup to convey information about all possible keys (even though some of them might be empty), so I can go like this:
var statistics = from grouping in myLookup
select new {grouping.Key, grouping.Count()};
which works with dictionary of enumerables, but unfortunately does not work with ILookup. It is just impossible to have entries where grouping.Count()==0, as with IDictionary.
As John Skeet states,
There’s one other important difference between a lookup and a dictionary: if you ask a lookup for the sequence corresponding to a key which it doesn’t know about, it will return an empty sequence, rather than throwing an exception. (A key which the lookup does know about will never yield an empty sequence.)
Now, what is wrong if ILookup allowed empty groupings? In order to have the best of both worlds I am about to add Filter() extension method for ILookup that does just this, but need to resolve a problem that Linq does not allow to create empty IGroupings (so I have to implement my own class), but I feel that maybe I am doing something against design principles of Linq.
Example
Two options:
1) you could create a nice, straightforward singleton-esque EmptyLookup class as follows:
var empty = EmptyLookup<int, string>.Instance;
// ...
public static class EmptyLookup<TKey, TElement>
{
private static readonly ILookup<TKey, TElement> _instance
= Enumerable.Empty<TElement>().ToLookup(x => default(TKey));
public static ILookup<TKey, TElement> Instance
{
get { return _instance; }
}
}
2) You can create a singleton class for empty lookups.
public sealed class EmptyLookup<T, K> : ILookup<T, K>
{
private static readonly EmptyLookup<T, K> _instance
= new EmptyLookup<T, K>();
public static EmptyLookup<T, K> Instance
{
get { return _instance; }
}
private EmptyLookup() { }
public bool Contains(T key)
{
return false;
}
public int Count
{
get { return 0; }
}
public IEnumerable<K> this[T key]
{
get { return Enumerable.Empty<K>(); }
}
public IEnumerator<IGrouping<T, K>> GetEnumerator()
{
yield break;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
yield break;
}
}
then you can write code like this:
var x = EmptyLookup<int, int>.Instance;
/*The benefit of creating a new class is that you can use the "is" operator and check for type equality:*/
if (x is EmptyLookup<,>) {
// ....
}
There is no wrong in keeping empty groupings is lookup, it's just that lookup does not support it because of it's nature in Linq.
You have to create an extension method by yourself.
I have a user defined class that I want to create a public List as part of. I want the List to be a List of delegate functions that I can add to and set each List Member to a delegate function. I want this list of functions to be part of the class I instantiate, so it follows the instance of the class as I pass it to other functions. I need the ability to call the delegated functions via a foreach loop, so it also has to be IEnumberable.
I've been trying for several hours, what I have may or may not do part of the job. When it started looking like I needed to write my own IEnumberation routines for the custom List, I realize I was in way over my head and came here.
This is the code I have:
public delegate List<ChartTestModel> MyDelegate<T>(T i);
public class DelegateList<T>
{
public void Add(MyDelegate<T> del)
{
imp.Add(del);
}
public void CallDelegates(T k)
{
foreach (MyDelegate<T> del in imp)
{
del(k);
}
}
private List<MyDelegate<T>> imp = new List<MyDelegate<T>>();
}
I don't even know if this does what I want it to or not. I know I can't ForEach through it, though. It's written entirely from pieced together code from looking on Google. I barely understand what it's supposed to do.
I don't see why you need a custom class at all. Just use List<T> where T is whatever delegate type.
List<Action> actions = new List<Action>();
actions.Add(() => blah blah);
actions.Add(Whatever); // Whatever() is a method
// now run them all
actions.ForEach(a => a());
IEnumerable<T> is simple to implement, particularly when you have a collection as a member of the class. All you need to do is define appropriate GetEnumerator methods, and the easiest thing to do is return the enumerator of the underlying collection.
class YourClass : IEnumerable<SomeClass>
{
List<SomeClass> list = ...
public IEnumerator<SomeClass> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Here, you implement methods for implicitly for IEnumerable<T> and explicitly for IEnumerable. (You have to implement both as IEnumerable<T> inherits IEnumerable.)
For your specific class, you might have
public class DelegateList<T> : IEnumerable<MyDelegate<T>>
{
// ...other class details
private List<MyDelegate<T>> imp = new List<MyDelegate<T>>();
public IEnumerator<MyDelegate<T>> GetEnumerator()
{
return imp.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
I hope this is userful to you.
static void Main(string[] args)
{
var delegateFuncs = new List<Func<string , string>> {
l1=>{ return "at1:" + l1;} ,
l2=>{ return "at2:" + l2;} ,
l3=>{ return "at3:" + l3;} ,
l4=>{ return "at4:" + l4;}
};
string parameter = "test";
foreach (var f in delegateFuncs)
{
Console.WriteLine(f(parameter));
}
Console.ReadLine();
}
I'd like to test if an id was not yet known or, if it is known, if the associated value has changed. I'm currently using code similar to this, but it is hard to understand for those not familiar with the pattern. Can you think of a way to make it more readable while keeping it short in LOC?
string id;
string actual;
string stored;
if (!someDictionary.TryGetValue (id, out stored) || stored != actual) {
// id not known yet or associated value changed.
}
You can write an extension method with a good name:
public static class Utility
{
public static bool ValueChangedOrUnknown(this Dictionary<string, string> dictionary, string id, string actual)
{
string stored = null;
return (!dictionary.TryGetValue(id, out actual) || stored != actual);
}
}
so later you can use
string id;
string actual;
if (someDictionary.ValueChangedOrUnknown(id, actual) {
// id not known yet or associated value changed.
}
So I would most probably break it up and give it meaningful names. This is more to read, but you don't need much to say in comments:
bool isKnown = someDictionary.TryGetValue (id, out stored);
// can only change when it is known
bool valueChanged = isKnown && stored != actual;
// quite self-explanatory, isn't it?
if (!isKnown || valueChanged)
{
}
wrap each part of the || into its own method or property, than you can write it like this
if ( IdIsNew() || IdChanged())
Duality.
if (!(someDictionary.TryGetValue (id, out stored) && stored == actual)) ...
Not sure if it is more readable though... but it's good to know.
It looks fine to me...reads as easy as any other 2 condition if statement. About the only thing I'd possibly change is to flip the negations for an early exit:
if (someDictionary.TryGetValue(id, out stored) && stored == actual) {
return;
}
// store new value
I don't see any confusion in it at all, have never thought of it as a particularly troublesome idiom, and humbly suggest that those C# devs confused by it get used to it. It's common, succint, and gives as many LOC to the problem as it deserves. Turning it into 10 lines of code makes it way too important.
If I used it often, an extension method named something like ContainsEqualValue would be appropriate - but I'd use the exact same code in the extension method as you have.
I'd prefer a new method:
public bool ShouldSetValue(Dictionary someDictionary, object id,object actualValue)
{
string stored;
if (someDictionary.TryGetValue (id, out stored))
{
if (stored != actualValue)
return true;
}
else
{
return true;
}
}
then in the existing method I'd just:
if (ShouldSetValue(someDictionary,id,actual))
{
someDictionary[id]=actual;
}
An extension method would be slick:
public static class DictionaryExtensions
{
public static bool ShouldAddValue<TKey, TValue>(this Dictionary<TKey, TValue> someDictionary, TKey id, TValue actual)
{
TValue stored;
return (!someDictionary.TryGetValue(id, out stored) || !stored.Equals(actual));
}
}
Usage:
someDictionary.ShouldAddValue("foo", "bar")
If you mean that you have to do this repeatedly, and it is long and ugly, abstract the logic to another class and use an extension method.
public static class DictionaryExtensions
{
public static DictionaryChecker<TKey,TValue> contains<TKey,TValue>(this IDictionary<TKey,TValue> dictionary, TValue value)
{
return new DictionaryChecker<TKey,TValue>(value, dictionary);
}
}
public class DictionaryChecker<TKey,TValue>
{
TValue value;
IDictionary<TKey,TValue> dictionary;
internal DictionaryChecker(TValue value, IDictionary<TKey, TValue> dictionary)
{
this.value = value;
this.dictionary = dictionary;
}
public bool For(TKey key)
{
TValue result;
return dictionary.TryGetValue(key, out result) && result.Equals(value);
}
}
Now replace your code with:
if(!someDictionary.contains(actual).For(id)){
// id not known yet or associated value changed.
}
public T GetValue(int id, object actual)
{
object stored;
if (someDictionary.TryGetValue (id, out stored) || stored == actual)
return stored;
return new object();
}
While I recognize that the "try" pattern is necessary, I dislike implementations which require an "out" parameter. It would seem much more useful have functions similar to TryGetValue:
TryGetDictValue(dictionary, key) returns null if key is not in dictionary
TryGetDictValue(dictionary, key, defaultValue) returns defaultValue if key is not in dictionary
TryGetDictValue(dictionary, key, valueReturningDelegate) invokes the supplied delegate if key is not in dictionary and returns its result
In every case, the return type of the result would be that of the dictionary's data.
It's too bad there's no way to sneak into a time machine and make such things be methods of Dictionary. On the other hand, one could implement them as static functions taking a dictionary as the first parameter.