A message from our CEO about the future of Stack Overflow and Stack Exchange. Read now.

New answers tagged

0

It'll add more work if you use interface since your models are different, only one property (Mobile) is the common one, and you'll add Reflection to the equation as well. Even if you used a generic method, you'll add extra work to it. So, in your case, your best approach would be to use overloads (which you've already done) and keep it simple, but you've ...


2

I have modified yours, (not tested), but I want to share it just to give you some insights, not the best design, but I felt I need to share it. //singleton class public sealed class HttpRequestClient { internal enum MethodType { GET, POST, PUT, DELETE } internal enum RequestContentType { JSON, XML, x_www_form_urlencoded } ...


1

You can do it without the IEqualityComparer but does get a tad bit more complex. Taking the gist of PairWithPrevious You can create an extension that keeps track of the previous value. The code that makes this look complex is the nullable decimal from the seed data. We do this so that we know it came from seed data and we can skip it. public static ...


3

Good implementation. Few minor bits: Mark _httpWebRequest as readonly as you're not assigning (nor want anyone to assign) to it outside of the constructor. Extract an interface (IHttpRequestBuilder) and have each method return that rather than the concrete class. This will allow for additional implementations or mocking for unit testing other parts of your ...


3

My implementation works just fine, until we go over 2^31 due to compare not doing unsigned comparison. The "incompleteness" of the set of comparisons is an old problem, and the workarounds are also old. Here are some options, with different trade-offs: x >=u y -> max_u(x, y) == x. With SSE4.1 or later, PMAXUD exists, so this is supported. It's greater ...


2

You're right, the way you're mocking the methods is tightly coupling the sequence of events, even though you don't really care about the order. What you really care about is that given a list, both methods are called, with the input/outputs chained and the overall output is the list without the filtered items. You can achieve this by rewriting your test: ...


1

I see what you are trying to achieve, while your question does not fully meet the Code Review rules, but I guess some inputs won't hurt specially in my free time ;). In my opinion, You should use DateTime instead of string and int. You should combine Talk and Slot, as it should be only one class that hold the meeting details (subject, time, and place .....


3

Heslacher and Henrik Hansen have given you good insights. In your case, Replace would be more appropriate to use as Henrik Hansen pointed out. The only addition that I would add is you can use Linq to do the same : var result = items.Select(item => string.Format("{0} Car", item.ChildName.Replace(item.Name, string.Empty).Trim())).ToList(); and also ...


3

I see no reason why you use IndexOf() at all. string.Replace(string, string) do the search for you and replaces all occurrences in the string anyway. And if the searched string is not found it just returns the original string. So your algorithm can be reduces to: foreach (Item item in items) { Console.WriteLine($"{item.ChildName.Replace(item.Name, "...


4

Because you use the returned value of IndexOf() only to check if it is > -1 a more readable way would be to use Contains() instead of IndexOf(). Internally Contains() does mostly the same than your comparison of the returned value. In the reference source of Contains() you will find [Pure] public bool Contains( string value ) { return ( IndexOf(...


2

I asked a very similar question here The thing that came out of it that I think you should think about is that there's no need to add Get / Post etc. to the interface. You can handle all that with extension methods. The answer to my question helped me with that. Here's the interface that I ended up with. Much simpler. Code Reference /// <summary> ///...


2

Whether or not code meets SOLID principles is often most apparent when you want to re-use the code for a similar purpose. So, given the code you've written, look at it from the perspective that it is not a Connect4 implementation but a XInARowGameEngine (with ConnectFour constraints built-in). So, in other words, consider what would need to be changed to ...


2

Without running the code myself, it seems you've done a pretty good job. There are just a couple things I would point out: Names Default Value Your dependency property for Names is declared as follows: public static readonly DependencyProperty NamesProperty = DependencyProperty.Register( "Names", typeof(ObservableCollection<...


1

Values of the Base class should have protected set;. In Mesh there is inconsistency with properties. Most are not readonly while some are. Depending of whether or not those properties should be readonly you may remove Values initialization as well as xn and yn computation from Compute. Furthermore, regardless of previous points, depending on whether or ...


1

Final version of the class, incorporating changes suggested by CharlesNRice, and removing the unnecessary callback method. public class TcpListenerEx : TcpListener { #pragma warning disable 618 [Obsolete("This method has been deprecated. Please use TcpListenerEx(IPAddress localaddr, int port) instead. https://go.microsoft.com/fwlink/?linkid=14202")] ...


2

Naming guidelines are in: For returning named tuples use PascalCased identifiers: https://github.com/dotnet/corefx/issues/33553#issuecomment-531420515 Usage guidelines are in: Unless you're named something like GetOffsetAndLength, don't use tuples (Tuple<T1, T2, ...>, ValueTuple<T1, T2, ...> or (T1 T1, T2 T2, ...) as a return type. (Same link) ...


1

string sourceFile = System.IO.Path.Combine(demoFileLocation, fileName); string destFile = System.IO.Path.Combine(liveFileLocation, fileName); if (!System.IO.Directory.Exists(demoFileLocation)) { resultStatus.ResultType = Result.Code.Error; resultStatus.Message = "Files cannot be located"; return resultStatus; } It would be better to check ...


2

You shouldn't store the cancellationToken. If someone was to call AcceptTcpClientAsync twice it would overwrite it. Also it starts making your async call keep state and that's not something you want to do or even need to do in this case. Also need to wrap the Register into a using statement such as // Register a Callback to be executed when the token is ...


2

public class ReportData { public ReportData(IEnumerable<ReportColumn> columns) { Columns = columns ?? throw new ArgumentNullException("No valid columns available"); } public IEnumerable<ReportColumn> Columns { get; set; } } The Columns property should be get-only. public string ColumnName { get; set; } public object[] ...


4

Your code has lots of duplication. You can make it more readable: private bool FilterLicenseList(object item) { var license = item as LicenseEntry; return FilterString(Filter.Firm, license.Firm) && FilterString(Filter.RegistrationCode, license.RegistrationCode) && FilterString(Filter.LicenseCode, license.LicenseCode) ...


3

Firstly, unless there is something you are not showing depending on the 'allChunks' list, I think that you could just remove it. Chunks appear to be either loaded or unloaded and all you will be doing is moving chunks between these two collections. The following line, jumps out at me as a possible slow operation: loadedChunks.ContainsValue(...


0

I belive your WCF service should always be accepting the Models. Like JSON code should be converted into Entity Models and then pass to WCF service. In this way you can make your code loosely coupled.


0

Remove logs from Starup.cs and add the logging into every method. You can override the onException method, where you can write your own customized message and exception


2

What don't you like about it? There's a very small space where a C++ exception could occur leaking the vector memory. If the ExrDepthMapExtractor or extractDepthMap throws, there's no way to clean the vector memory. You could just put something in the catch block. You could memcpy the pixel memory from C++ to C# instead of looping. Or share memory the ...


3

Option 1) You can create a DataRelations between the two Data Tables and change the loop to fill in both classes at the same time. This would require you do change the code that converts the results set into C# classes. Microsoft has an example of GetChildRows and navigation here Option 2) Otherwise you could also create a DataView and set the Sort ...


2

Extension methods Notice that I add this to the first arguments of all the functions to allow calling them like points.Area() instead of Area(points). Polygon Vertices vs. Edges The biggest problem I see is that you represent the polygon as a list/array (generaly an enumerable) of points. Well that's not bad on it's own. But the fact that all your ...


1

I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the DataGridView. But, their id value is always 0. And, I need for the id value to be unique. When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the ...


2

You are not really extracting a substring, you are only printing a substring. A string consists of single characters of type char. Create an array of chars and then convert it to string var characters = new char[numberOfLetters]; for (int i = 0; i < numberOfLetters; i++) { characters[i] = word[i + start]; } string output = new String(characters); ...


2

your non-common code is the line with the formula, so this is what you have to move to the outside, and pass as a parameter. public static float Area<T>(IReadOnlyCollection<T> points, Func<T, T, float> func) { float a = 0; for (int i = 0; i < points.Count; i++) { var p1 = points[i]; ...


2

I have only 2 things to note. Returning the same status code as the remote server could lead to confused clients of your API due to incorrect status codes. What if the remote server has returns a 5xx status code? Your server didn't have an internal server error, the remote did, but then why is your server returning a 5xx status code? Instead, I recommend ...


4

Depending on how many points you'll be dealing with, you could go one step further. Since you're only using 2 points from the Vector3, it's fairly simple to cast the Vector3's into Vector2's. public static float Area(List<Vector2> points) { float a = 0; for (int i = 0; i < points.Count; i++) { var p1 = points[i]; var p2 ...


1

You could avoid a lot of duplicated code if you call one overloaded method from the other overloaded one. An IList<T> can be easily changed to a [T] array by just calling the ToArray() method of that List. This would result in e.g public static float Area(List<Vector3> points) looking like so public static float Area(IList<Vector3> ...


1

1 + 2 + ... + n = n * (n + 1) / 2, for example, 1 + 2 + 3 = 3 * (3 + 1)/2 = 6, so the \$O(N)\$ is that: sum the array, O(n) (no sorting) check sum == n * (n + 1) / 2


-1

public static class ObjectExtensions { public static object GetValueByName(this object o, string name) { PropertyInfo myProperty = o.GetType().GetProperty(name); return myProperty.GetValue(o, null); } public static string Parse(this string str, object o) { ...


1

GetFileBatches is enumerating fileInfoCollection twice. One for Any and once for groupby. By default Rx runs same thread. You could test this by logging Thread.CurrentThread.ManagedThreadId and seeing the values. The RawDepthMapsProducer isn't adding anything and just adding over head since its all on the same thread. You can read more here. Right ...


3

It appears the goal here is to provide parameters to a resolve operation using a different format, something string-based. This appears to be primarily useful in a service location (manually executing Resolve) scenario rather than true DI, so I would caution you to be careful. Since this started as an Autofac solution, I'll post an answer based on Autofac. ...


1

GitHub and NuGet The right way would be to do not depend on Autofac but support it through AutofacSeriveProvider as many other IoC containers. So now I have this for ioc://: namespace System { public static class ServiceLocator { public static T GetService<T>(this IServiceProvider provider, string uri) => provider....


2

My take on this: For console apps, I like to use a more OOP approach. A Message class to hold a string array to handle a multiline message, and if the message requires a response a string of the characters allowed, will allow you to replace all those string literals with named variables: class Message { public String[] message { get; } public ...


2

Except all that @JAD said, which I totally agree with. I will give me five cents also after taking your comment in mind. I want to cancel the other pings when one of the ping responses is successful. This should be the default behaviour - so I don't want to expose this implementation detail to the other clients. First and foremost, there is a much ...


2

The whole if..else..if..else inside the first loop is senseless because each branch does exactly the same. Using Split('|') and combining the resulting array with one space " " is the same like replacing | by a space. The Regex regx = new Regex(sentenceSeparator); is superflous because you don't use regex at all. The loop for (int i = 1; i < ...


2

It doesn't make sense to have the CancellationTokenSource private like you have now. Who is going to be able to cancel the operation? The user of your class can't access the source or provide their own token. The class doesn't offer any API to cancel. Instead, you should alter the private bool IsOneOfTheHostsAvailable() method to accept a CancellationToken ...


1

I've got a few suggestions to improve your application. I would suggest using a few functions to clean up the organization of your code. This will also allow you to move some off your logic away from your main application logic which will help to remove duplicate code. First main change I would suggest is to move away from the array of strings to represent ...


0

Right at the start we can turn your hands array in to a dictionary so we can compare Int insted of String, which is way faster. In such a small application it is not mandatory such optimizations, but it is good to consider in the long run. Dictionary<string, int> handsValues = new Dictionary<string, int>() { {"...


1

So after updating my source code it looks that it performs fast enough and allocates no memory. Here are benchmark for comparing the most popular methods of generating GUIDs. Runtime=.NET Core 3.0 Force=True Server=True | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |-...


6

You want to reduce both computation time and memory allocation. Memory allocation itself takes time, so that's a good place to start -- try to find all the places where you're allocating memory and see if they can be avoided. ArrayPool<byte>.Shared.Rent(16); can avoid an allocation, but not always. Can we do better? Turns out we can; we'll see how. ...


1

You should not pass an IQueryable as a result. Convert it into an object or list of object and close the existing connection before passing it as a result. IQueryable is used to query the data before fetching it and hence the connection will stay open. Basically, it's similar to Connection.open() and then not closing the connection.


1

You use yield properly, it's OK to yield from inside nested loops. But all the code behind your first foreach is kind of useless, it's not doing anything useful. First the yield break is useless, cause there are no more yields following, there are no more return values produced no matter if IsLeaf true or false. Iteration ends anyway. Second you fill up ...


0

public static int[] PatternIndex(string given, string pattern) { var patternList = new List<int>(); if (string.IsNullOrEmpty(given) || string.IsNullOrEmpty(pattern)) return Array.Empty<int>(); for (int i = 0; i < given.Length - pattern.Length; i++) { if (given.ToLower().Substring(i, ...


2

If you want to see how performance is you need to get the user input out of the loop. I'm assuming you don't want to measure the time it takes someone to type in or paste in the data elements. You don't need the variable how_many as it will always be the same as the Count of which, which by the way isn't a good name for a variable even something like ...


3

I don't know much about C#, so this answer will focus solely on generic stuff. Performance problems in image processing applications usually happen inside loops over all pixels. I'm focusing on this section of the code: for (int x = 0; x < tempImg.Width; x++) { for (int y = 0; y < tempImg.Height; y++) { double distence = GetDistance(...


Top 50 recent answers are included