The Stack Overflow podcast is back! Listen to an interview with our new CEO.
38

is the current implementation 'safe'? Absolutely not. The fact that you had to ask this question indicates that you do not understand enough about threading to build your own mechanisms like this. You need to have a deep and thorough understanding of the memory model to build these mechanisms. That is why you should always rely on the mechanisms provided ...


31

First: congratulations, you have rediscovered the error monad. https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Error.html Second: as noted in the comments, C# already has the concept of "wrap up either a value or an exception, namely, Task<T>. You can use Task.FromException and Task.FromResult to construct them. Of course Result on ...


31

Why didn't Microsoft include this in the .NET framework? Probably because it can be realized in one line with Select: source.Select(x => x.Equals(oldValue) ? newValue : x) or with 2 lines as extension method if the function is needed frequently. public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T ...


28

You say cache I say memory leak. You haven't given much thought to your eviction policy yet and that's 95% of the work in writing a decent cache. Your expired entries are only removed when someone tries to access them. Consider the case when the cache is used poorly - i.e. you end up caching a huge number of things that are only accessed once. Without a ...


24

I cannot comment about the speed because I didn't benchmark it but there are two obvious improvements. add an IEqualityComparer<T> as a third parameter so that you can use a custom one if necessary (e.g. own typs) use foreach instead of the enumerator Example: public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T ...


21

The problem, however, is that this means when creating my classes, I need to ferry around this TPos generic construct to places where it doesn't make sense to define it. I'm left creating new Player<Vector3> or Player<Int2> instances all over the place when really I just want to be creating a Player. Yes, specifying Player<Vector3> each ...


18

If done cleverly, you can get away with a single method to get the input of any type: static T GetInput<T>(string message, Converter<string, T> transform) { Console.WriteLine(message); return transform(Console.ReadLine()); } All you need to do is pass in a transformation function (the Converter<TInput,TOutput> delegate is ...


18

Short version: it looks like you're just trying to get a per-type ObjectCache. That's a basic singleton pattern, so I'm unsure what you're trying to gain through all this extra cruft in the class. If it were me, I would consider the following code: public static class GlobalTypedObjectCache<T> { public static ObjectCache Cache { get; private set; }...


18

Having backported Lazy to .NET 2.0, I want to offer a variant... First of all, this looks a lot like LazyInitializer. If that works for you, then there is no need to go about creating a Lazy<T> variant. With that said, let's continue... Before going into the code, let us see some things that may go wrong: The ABA problem Thread visibility/Code ...


17

You should create a Dictionary<Type,Type> that would associate your object's type with their DTO equivalent, so you wouldn't need any if. Then you can use the dictionary to find the types to map. ex : //This should be instanciated wherever you want, but try to do it only once. //The dictionary should be static dictionary = new Dictionary<Type,...


15

Your implementation is not bad for a no-LinQ solution. But there's always room for improvement. First I'll provide a LinQ solution that provides a clean way to return a chunked list: public static List<List<T>> Split<T>(List<T> collection, int size) { var chunks = new List<List<T>>(); var chunkCount = collection....


14

It may appear to some as code smell, but it's a practice in use in the .net framework defined as 'marker interfaces'. IReadOnlySessionState is one of these and as per the documentation: Specifies that the target HTTP handler requires only read access to session-state values. This is a marker interface and has no methods. So, to answer your question, ...


14

Your interfaces are inconvenient, and you are falling in to a trap of convenience that actually leads to inconvenience..... let me explain... C# makes it easy to create the getter/setter methods for interfaces/classes. There are three places I can see where your use (abuse) of this convenience leads to poor usability of your interfaces: public interface ...


14

Two parts to this review: the 1-liner for the newInstance() the general mechanism of the method newInstance() This code will work, but only for a subset of Collections. For example, there are many Collection implementations that do not have an accessible default constructor. What if the input collection is: Collection<String> input = Arrays.asList(...


14

You should probably add IConvertible restriction on T, since it is used by Convert.ChangeType method. Also this check: typeof(T) == x.GetType() looks like an overhead. Convert.ChangeType does nothing if types match. For example, check out Int32 sources: int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } So you might as well just ...


14

Memory management You never delete[] arr;, which leaks memory. Not a good thing! There are multiple ways to fix this: Adding correct calls to delete[] arr; in the right places (remember exceptions, assignments and so on!), which is rather bug-prone. Also, new T[size] default-constructs size objects of type T in the contiguous memory. This requires T to be ...


13

There are 4 ways to a solve this: Solution 1: You can define a fixed width STD_LOGIC_VECTOR (SLV), which can be used to construct other vectors (let's call them STD_LOGIC_VECTOR_VECTORs (SLVV). subtype T_SLV_8 is STD_LOGIC_VECTOR(7 downto 0); -- define a Byte type T_SLVV_8 is array(NATURAL range <>) of T_SLV_8; -- define a new ...


13

I'm not sure if you understand what boxing means because you use an int in the example. Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. and When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. and Unboxing extracts ...


13

is there anything else I'm missing that I should be concerned about in a high traffic application? Yes, your Lazy<T>.Value isn't generic anymore but an object and if Func<T> returns a value type then a lot of un/boxing will take place. This might hurt performance. I think a LazyFactory.GetOrCreate<T>(...) would do a better job.


12

First off, never lock on this. You never know who else is locking on that instance. Conversely, clients don't know that the cache is locking on itself either. For example, this seemingly innocent code would lead to a deadlock: //Thread A lock(cache) lock(someObject) { //do something } //Thread B lock(someObject) { //here, the cache will lock on ...


12

Please correct me if I am wrong, but isn't such scenario possible with accepted answer? public T Swap() { var swappedBuffer = Interlocked.Exchange(ref _current, Next); // 1 Next = swappedBuffer; // 2 return swappedBuffer; // 3 } And it goes like that: (A and B denotes some object of type T): _current = A Next = B Thread 1 executes Line 1: ...


12

Performance bug private void BubbleUp(T element) { int elementIndex = _elements.IndexOf(element); ... This is \$O(n)\$, which completely oblitirates \$O(\log n)\$. (It takes over a second on 2,5 GHz CPU to insert 10 000 elements using your version.) Same applies to BubbleDown. Instead of passing the element to BubbleUp and BuggleDown, pass the ...


12

Small things Your code styling is generally good, but a few possible improvements: You can add a second generic type parameter to your method to avoid the need to cast to object. i.e. public static List<TIn,TOut> MergeListData<TOut>(List<TIn> collection) You can probably use a more general collection than List<object> for your input ...


12

I think, it can be simplified just a little bit: static object Deserialize(byte[] buffer, Type type) { using (StreamReader sr = new StreamReader(new MemoryStream(buffer))) { return JsonConvert.DeserializeObject(sr.ReadToEnd(), type); } } NB: StreamReader releases/disposes MemoryStream, so you don't have to encapsulate that in a using() Or You ...


11

An empty interface is a code smell. In C# you can use attributes to mark a class instead of making it implement an empty interface. As I suggested in my comment, you can use reflection to build your Map instead of receiving it as input, and failing on discrepancy. With the power of attributes, you can add functionality by marking which properties you want ...


11

This class looks reasonably complete, and fully usable. There are some issues I see that may affect the experience though, and also some suggestions about a better way to do it... Issues: Why do you reject null values? Your implementation works well even if the item is null, so why exclude it? The NullPointerException in the constructor is not a problem, ...


11

Compiler Warning This line gives you a compiler warning because it's not using generics: List activeList = listOfLists.get(pageNumber); it should be List<T> activeList = listOfLists.get(pageNumber); Empty list input If the input is an empty list, then the output will be a list containing one empty list. I think it would be more reasonable if the ...


11

Consistency: Don't mixup using var and declaring your variables explicitly. Choose one of the two, preferably var. Combining methods: Use method chaining to shorten your code. There's no need to create a variable for every step your code does. This: var materialStringArray = materialIDs.Split(','); var materialIdsArray = materialStringArray.Where(x => ...


11

Here are a few remarks. I'm not perfect or write perfect code but I hope these tips will help write better code: Naming consistency: It would be easier to understand if the names of your two methods had opposing names. For example: SerializeToFile and DeserializeFromFile. It's obvious that deserialization will return an object, omit that in the name. Also,...


11

There's certainly room for improvement. Move that that Select(stringFieldFunction).ToList() out of the while loop. Iterating an IEnumerable might be quite expensive, and there's no need to repeat that work when you find a duplicate. Select only those strings that have originalString as a prefix. That will reduce the amount of items you need to check against ...


Only top voted, non community-wiki answers of a minimum length are eligible