Tag Info

New answers tagged

0

In general, I wouldn't store the data for your solution based on the way that you want to display it. That leads to very specific solutions that will make things difficult when your needs change. I would break things down in terms of entities in your solution and then create a set of LINQ Queries that would generate your display data when it is time to ...


6

There is another reason why you may want to inherit from a generic type. Microsoft recommend avoiding nesting generic types in method signatures. It is a good idea then, to create business-domain named types for some of your generics. Instead of having a IEnumerable<IDictionary<string, MyClass>>, create a type MyDictionary : ...


1

Does laziness within an application naturally yield a greater chance of race conditions? Of course it does. Properly written multithreaded code will not have race conditions, of course; race conditions are caused by not thinking about all the possible outcomes of ordering between multiple threads. This is not to say, however, that lazy loading directly ...


0

There are three possible reasons why someone would try to do that off the top of my head: 1) To simplify declarations: Sure StringList and ListString are about the same length but imagine instead you're working with a UserCollection that's actually Dictionary<Tuple<string,Type>, IUserData<Dictionary,MySerializer>> or some other large ...


1

One of the most important things when using a programming language is understanding what it's weaknesses are. As many languages have substantially different weaknesses, it is often a very bad idea to directly port code from one to another. In both examples you have provided, you are presented with a fairly severe typing issue. Even the dictionary has a ...


-1

I may do class WidgetList : List<String> { /* no further code!*/ } to give some syntactic meaning to the strings Or I may create a class Widget : String{} and use List<Widget>. Simply depending on which I felt conveyed the codes intent better. but the construct you point out does not seem to add a great deal to the clarity of the code. ...


6

I think you need to look into some history. C# has been used for a lot longer than it has had generic types for. I expect that the given software had its own StringList at some point in history. This may well have been implemented by wrapping an ArrayList. Then someone a to refactoring to move the code base forward. But did not wish to touch 1001 different ...


1

In some cases it is impossible to use generic types, for example you can't reference a generic type in XAML. In these cases you can create a non-generic type which inherits from the generic type you originally wanted to use. If possible, I would avoid it. Unlike a typedef, you create a new type. If you use the StringList as an input parameter to a method, ...


7

I can think of at least one practical reason. Declaring non-generic types that inherit from generic types (even without adding anything), allows those types to be referenced from places where they would otherwise be unavailable, or available in a more convoluted way than they should be. One such case is when adding settings through the Settings editor in ...


10

I don't know C# very well, but I believe this is the only way to implement a typedef, which C++ programmers commonly use for a few reasons: It keeps your code from looking like a sea of angle brackets. It lets you swap out different underlying containers if your needs change later, and makes it clear you reserve the right to do so. It lets you give a type ...


-2

I'd say it is not good practice. List<string> communicates "a generic list of strings". Extension methods apply. Less complexity is required to understand; only List is needed. StringList communicates "a need for a separate class". Extension methods may apply (check the actual type implementation for this). More complexity is needed to understand the ...


27

In principle there's no difference between inheriting from generic types and inheriting from anything else. However, why on earth would you derive from any class and not add anything further?


1

The Matrix.MeshGrid method takes inputs as type of T[] (not T[,]). Method signature: public static Tuple<T[,], T[,]> MeshGrid<T>(this T[] sequence1, T[] sequence2); Example: var xi = new double[] {1, 2, 3, 4, 5}; var yi = new double[] {6, 7, 8, 9, 10}; Tuple<double[,], double[,]> grid = Matrix.MeshGrid(xi, yi);


2

Let me ask a question : what you happen if in your PHP version I would write: // PHP class Sample { public function __construct() { $dispatcher = new EventDispatcher(); $dispatcher->addListener("sample.event", array($this, "onEvent")); $dispatcher->dispatch ("sample.event", new WarnEvent()); // oops? } ...


6

I wouldn't say it's an abuse. It's certainly something you can do with generics, and it sometimes makes your code cleaner. Here's the caveats: While it's super easy to go from generic to Type it's very difficult to do the opposite. If your caller is likely to have a Type variable rather than calling your stuff with an explicit type... maybe reconsider. It ...


0

I'd suggest doing both! Those on* methods are the ideal place from which to raise those events. (Well, it must have some merit; that's the way most, if not all, of the .Net Windows Controls work). internal class Button2 : System.Windows.Forms.Button { protected overrides void onClick( EventArgs e ) { if ( ! ...


-2

+ concatenation uses String.Concat anyway - String itself doesn't expose a + operator. So for example: int i = 10; string x = "hello" + i; is compiled into: int i = 10; object o1 = "hello"; object o2 = i; // Note boxing string x = string.Concat(o1, o2); Whereas calling ToString directly will avoid boxing and call the Concat(string, string) overload. ...


3

Of the now partially outdated but still useful article from MSDN: "When to Use Delegates Instead of Interfaces (C# Programming Guide)", a few of the rules-of-thumb stand out: Use a delegate in the following circumstances: (3) The caller has no need to access other properties, methods, or interfaces on the object implementing the method. My ...


13

Instead, you should use string formatter. It's easier to format your number into string representation or localization. e.g.: string expression = string.Format("Expression: {0} + {1} = {2}", a, b, sum); More info on MSDN. However, string formatter is less readable (and maybe also performance) than string concatenation.


18

ToString usage No, you shouldn't use ToString here. String concatenation automatically transforms non-strings into strings, which means that your two variants are nearly┬╣ identical: When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands. Source: C# Language Specification: ...


2

I definitely must have the IByteStream and the IFloatStream interface. Without a compelling reason, I definitely say you don't. Do you make a ByteList or a FloatList? No, you leave List be and let people parameterize it. This sort of aliasing can occasionally be useful, but more often it is a code smell that your interface/class is too abstract (or ...


2

You are right, DAL reference should NOT exist in the UI project. You should instead create DTO objects for sending/recieving data to your BLL. It can be a separate project called DTOs or can be included in the BLL by creating specific folders like Customer and placing its facade classes along with the DTOs in that folder. BLL will be responsible for mapping ...


6

Yes, what you're referring to is method chaining. You would add these methods to your class, and the return for each method would be the class itself. class Query { public string serverName { get; set; } public string tSQL { get; set; } public Query(string ServerName, string TSQL) { serverName = ServerName; tSQL = TSQL; ...


0

Have you ever listed items in a directory using ls -a ~/Downloads or dir C:\Users\user1\Downloads\ /P Now those "ls" and "dir" are commands/programs and the latter arguments are passed to the programs as string[] argv or sometimes int argc, char** argv. They provide arguments to the programs so they can behave accordingly. When you start a program ...


2

It is absolutely fine to have an interface that doesn't communicate how the implementation works. In fact that is the point of an interface, to hide implementation details! Your second option is fine in this scenario.


0

Use a caching mechanism that is independent of the stateless queries run by the user. Much in the same way database connections are pooled - ie you never open a new DB connection apart from the first time, every subsequent 'open' really fetches a previously used connection from a cache inside the DB client driver. You need to determine a method for handling ...


-2

Here's some guidance you can use on when to select Array and when to select List. Use Array when returning from a method. Use List as the variable when you are constructing the return value (inside the method). Then use .ToArray() when returning from the method. In general, use an Array when you don't intend the consumer to add items to the collection. ...


0

In general, holding a file open between user requests is not a good idea. There are several problems: The session can time out, leaving the file in limbo. In a busy system, this can lead to file handles running out. Many "enterprise" quality web containers serialize your session to a database when they are busy. You don't say what language you are using, ...


8

Your question has actually already been answered before. and seems also just as efficient in memory and performance as an array. It isn't. From the question I linked: List/foreach: 3054ms (589725196) Array/foreach: 1860ms (589725196) Arrays are twice as fast in certain important cases. I am certain the memory usage also differs non-trivially. ...


0

One important different is memory allocation. For example, traversing a linked list could result in a lot of cache misses and slower performance, whereas an array represents a contiguous chunk of memory holding multiple instances of some particular data type, and do traversing it in order is more likely to hit the CPU cache. Of course, an array of object ...


0

A 100-element array of some type T encapsulates 100 independent variables of type T. If T happens to be a value type which has a mutable public field of type Q and one of type R, then each element of the array will encapsulate independent variables of types Q and R. The array as a whole will thus encapsulate 100 independent variables of type Q and 100 ...


0

1) There is no multi-dimensional version of List. If your data has more than one dimension it will be very inefficient to use lists. 2) When you are dealing with a large number of small data types (say, a map where all you have is one byte for the terrain type) there can be considerable performance differences due to caching. The array version loads ...


3

You could use Sessions here but that has a few downsides. The oft-quoted one is the default configuration (in process) is fast but the session dies if the app pool gets restarted. Code-wise this means you typically need to check if your session has not died so you can handle it gracefully. This is fairly easy to do but it is some overhead. The bigger ...


1

If you're traversing all elements of a list, then no, an array is not necessary, 'next' or arbitrary 'selection without replacement' will do fine. But if your algorithm needs random access to the elements in the collection, then, yes, an array is necessary. This is somewhat analogous to "is goto necessary?". In a reasonable modern language it is not needed ...


1

Well, I found a use for arrays in a game I have been writing. I used it for creating an inventory system with a fixed number of slots. This had several benefits: I knew exactly how many open inventory slots the game object had by looking and seeing which slots were null. I knew exactly what index each item was in. It was still a "typed" array (Item[] ...


3

This is strictly from an OO perspective. While I can't think of a reason to pass just an array around, I can certainly see situations where an array representation internal to the class is probably the best choice. While there are other options that give similar characteristics, none seem as intuitive as an array for problems dealing with processing ...


21

The same reason I don't drive a truck when going to work. I don't use something that I won't use the features of. First of all an array is a primitive construct so an array is faster and more efficient than a List<> for sure, so your argument is not true. Array is also available everywhere and known by developers using different languages and platforms. ...


8

You need arrays to manage your collection of mutable structs, of course, and what would we do without those. struct EvilMutableStruct { public double X; } // don't do this EvilMutableStruct[] myArray = new EvilMutableStruct[1]; myArray[0] = new EvilMutableStruct() myArray[0].X = 1; // works, this modifies the original struct List<EvilMutableStruct> ...


0

The last MVC app I designed I had to hold onto a file through multiple pages before it was 'saved' (as at any point the user could cancel). I stuck it in Session and all has worked well since. That said, this feature doesn't get much use (10s of users at once) so I do not have data on how it scales. While the web is stateless and MVC design lends itself ...


3

In addition to reasons listed in other answers, array literal takes fewer characters to declare: var array = new [] { "A", "B", "C" }; var list = new List<string>() { "A", "B", "C" }; Using array instead of List makes the code a bit shorter and just a bit more readable in cases when (1) you need to pass any IEnumerable<T> literal, or (2) ...


0

Legacy compatibility. All form personal experience: Legacy programmers - my colleague uses arrays everywhere, has done for 30+ years, good luck changing his mind with your new fangled ideas. Legacy code - foo(array bar[]) sure you can use a list/vector/collection toarray function but if you not using any of there additional features its easier to use an ...


13

So why would I ever want to use an array? Rarely, you will have a scenario where you know that you need a fixed number of elements. From a design perspective, this should be avoided. If you need 3 things, the nature of business means that you'll very often need 4 in the next release. Still, when this rare scenario actually occurs, using an array to ...


3

This actually goes for other languages which have lists as well (such as Java or Visual Basic). There are cases where you need to use an array because a method returns an array instead of a List. In an actual program, I don't think an array will be used very often, but sometimes you know the data will be a fixed size and you like the small performance gain ...


2

I think the other answers are being a bit too simplistic. My approach would probable by to put it in configuration in code. I.e. keep the same data structure you were thinking for your configuration file, but don't put it in an external configuration file. Instead, build it in code. In a python world, I'd do something like (I don't know c# well enough to ...


0

I would regard the approach as being in many circumstances the best possible in a framework which does not allow interfaces to include public static helper methods. I would consider IFoo.Create() preferable to Foo.Create() if such a thing were allowed, but unfortunately (at least in .NET languages) it isn't. Despite the unfortunate naming of the factory ...


1

You can store the value as a number if you have a datatype that can represent more than choicescount possible values. In the case of 340, this is the number 12,157,665,459,056,928,801 which is just under 64 bits. So, you could hypothetically store this in a Unit64 (docs). This isn't a good idea. As soon as you add another question, you will overflow ...


3

An int represents a fixed number of bits (usually 32 or 64). This is a measure of information content; it is fundamentally impossible to store more than this number of yes/no decisions in it. With three-way decisions the arithmetic becomes slightly more involved because they represent fractional numbers of bits (two three-way questions contain slightly more ...


6

Which way is better? Based on what you've described, adding a new class is way better. why? Because editing a config is just as hard/painful as editing code, except it's tons more error prone and requires more work to setup - and nobody coming into your company knows what the hell this config is, or what format it's in, or where to find it. Now, ...


0

I have been pondering the same recently, and my tentative conclusion is that the mere question arises because the .NET Exception hierarchy is severely messed up. Take, for example, the lowly ArgumentNullException which might be a reasonable candidate for an exception you don't want to catch, because it tends to indicate a bug in the code rather than a ...


1

Often forgotten and possibly tangential to your question, when dealing specifically with .NET types, is CLS Compliance. Not all types are available to all languages built on the .NET Framework. If you're writing code to be consumed by languages other than C# and wish that code to be guaranteed to interoperate with as many .NET languages as possible then you ...



Top 50 recent answers are included