Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was searching for a solution for the problem I'm having in my project.
In the link below I found something usefull:
One Key to multiple values dictionary in C#?
However: isn't it better to use a Object in the dictionary instead of using a Tuple??
Object obj = new Object();
var dict = new Dictionary<KeyType, obj>();
foreach(KeyType kt in dict)
{
obj.X = value1;
obj.Y = value2;
}
Instead of:
var dict = new Dictionary<KeyType, Tuple<string, int, int, int>>()
I hope that there is someone who could help me. Thanks :)
You cannot do obj.X in C#, if obj is of type Object. But you can create a custom class derived from Object, which contains all the field and properties you need and use it inside the dictionary.
This would indeed be superior to the Tuple solution, since myObj.Speed is much more descriptive than myTuple.Item2.
Note, however, that Tuples have some features that your custom class might not have, for example, tuple1.Equals(tuple2) returns true if both have the same elements. With your custom class, Equals will check for reference equality, unless you override it.
No, it is not better to use object - you loose your strong typing.
If you are concerned about the verbosity of your code, you can always do something like this:
At the top of your document:
using MyDictionary = Dictionary<KeyType, Tuple<string, int, int, int>>;
Then your constructors do this:
var dictionary = new MyDictionary();
Instead of using Tuple I prefer to make a simple class with two/three fields. It's much cleaner solution and it's easier to use.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Adding primitive struct (eg. int) to a List:
int i=10;
List<int> list=new List<int>();
list.Add(i);
Versus:
Adding non-primitive struct (eg. KeyValuePair<int,int>) to a list:
List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
list.Add(new KeyValuePair<int,int>(10,20));
While adding the int struct to a list, we do not need to use the new keyword. But while adding the KeyValuePair struct to a list, we need to use the new keyword.
I mean to say, the following statement is not valid:
list.Add(new int(10)); //invalid statement
Though both int and KeyValuePair are struct's, they behave differently - one does not require instantiation before use (as far as the user is concerned). And the other requires instantiation before use.
Why can't we do the following instead:
list.Add(KeyValuePair<int,int>(10,20)) //omit the new keyword, as we were doing with an int
Coming from a C/C++ background, what does the new keyword exactly do in C#?
Does it just instantiate the underlying data type (and we are not sure whether the instantiated data type will lie on the Stack or the Heap). Or, are we sure that using the new keyword will allocate memory on the Heap (as it does in C++)?
what does the new keyword exactly do in C#?
It's all listed here. The most relevant one to this question is "constructor invocation". Structs and classes have constructors, and constructors create instances of structs and classes.
When you do:
new KeyValuePair<int,int>(10,20)
you are calling this constructor.
int, which is an alias for the Int32 struct, does not have a constructor that accepts a parameter of type int. This is the reason why you can't do:
new int(10)
Note that calling a constructor isn't the only way to create an instance of a struct. You can also do something like:
var defaultKVP = default(KeyValuePair<int, int>); // gets the default value of the type KeyValuePair<int, int>
// defaultKVP is an instance of KeyValuePair<int, int>! It's not null! Structs can't be null :)
The default value of a struct is defined by setting all its value-typed fields to their default values, and reference-typed fields to null.
The reason why an integer literal like 10 is an instance of the struct Int32, is, well, compiler magic. The spec says so, so it is implemented this way.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a dictionary that I would like to pass externally through a property but I would like to limit some features like the clear method. Here's the code that i've implemented.
// dictionary private declaration inside the class
private Dictionary<int, string> _value = new Dictionary<int, string>();
// here's the property declaration for access the dictionary outside the class
public new Dictionary<int, string> Value
{
get
{
return _value;
}
set
{
// here is where i'd like to avoid some dictionary features like clear() and give only the opportunity to add or change existing values
_value = value;
}
}
It’s possible through the “set” of this property to limit some of the features of the dictionary? Maybe using a switch or an if statement?
There are a ReadonlyDictionary that acts as a wrapper around a dictionary, and a corresponding IReadOnlyDictionary interface.
If you are on .Net core 3 there is also an ImmutableDictionary if the dictionary never needs to be changed.
If this is to coarse grained, you can always create your own wrapper that works however you want it to.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
EDIT 1: This question is about new features of C#, not about actual possibilities (where there is no such thing as new default()).
EDIT 2: There is actually a discussion about that reduction of redundancy # .DOTNET Foundation.
When declaring a member,
class MyClass {
AnyClass<WithLong<Generic,Declaration>> value =
new AnyClass<WithLong<Generic,Declaration>>();
}
is quite redundant.
We may find the following, more concise, less noisy:
AnyClass<WithLong<Generic,Declaration>> value = new default();
// or
AnyClass<WithLong<Generic,Declaration>> value = new();
// or
AnyClass<WithLong<Generic,Declaration>> value = new var();
Is there any benefit to the actual redundancy, or any risk on a more concise declaration that I haven't identified ?
Note 1:
var is actually a good way to reduce noise :
var value = new AnyClass<WithLong<Generic,Declaration>>();
My comment is about extending that concision to members.
Note 2:
A similar question has already been posted, but answers don't really care about redundancy & noise, which is unfortunate, because i think keywords like default, var are already intended to reduce code noise, and that is not a so futile question.
The C# team acknowledge this issue and they plan to remove extra noise when relevent.
In the specific case of Dictionary, you will have to wait until C#9.
Dictionary Literals introduces a simpler syntax to create initialized Dictionary objects without having to specify either the Dictionary type name or the type parameters. The type parameters for the dictionary are inferred using the existing rules used for array type inference.
// C# 1..8
var x = new Dictionary <string,int> () { { "foo", 4 }, { "bar", 5 }};
// C# 9
var x = ["foo":4, "bar": 5];
This proposal makes the work with dictionaries in C# simpler and removing the redundant code. In addition, it is worth to mention that a similar dictionary-syntax is used in other programming languages like F# and Swift.
source
Well no... I just read that the dictionary literals issue was rejected...
We think there are a number of interesting use cases around initializing data, particularly for things like immutable dictionaries. We don't find the existing syntax for initializing a dictionary that onerous, nor do we see it as a frequent pattern in code that would benefit much from a language feature. We thing that the general area of initializing data should be looked at again after we do records and withers. But this proposal doesn't feel compelling.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I dynamically created a Dictionary<string,object> and recursively assigned the object(dictionary's value) to either a string , Dictionary<string,string> or another Dictionary<string,object>. I have been able to write code to take out the information from the string levels but not when it is a Dictionary<string,object>.
I simply tried casting the value to a Dictionary<string, string> but an error is thrown saying the object cannot be casted to that.
I know for a fact that the underlying structure is a Dictionary<string, string>. How can I gather the information form the object.
You have to create an entirely new dictionary of the type that you want, and cast the values of the old dictionary to their actual type before adding them to the new dictionary. Of course, this doesn't actually take all that much code, because there are tools to obscure all of the work being done, but that work still needs to be done.
var newDictionary = oldDictionary.ToDictionary(pair => pair.Key,
pair => (Dictionary<string,string>)pair.Value);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been learning collection and generics and understood that generics were introduced to
provide more type safe containers and to improve the application performance by reducing number of boxing/unboxing.
But, If that was the case, why does the framework allows to create generics collection of type system.objects which can take any other type?
List<object> listObj = new List<object>();
listObj.Add(new Program1());
listObj.Add(new Program2());
Thanks in advance.
Yes the collection is List<T> is object not a type? object is a type like any other (being the base type doesn't make it any different) and therefor can be used as the type argument for generic collections, there is nothing wrong with that, just don't do it when you know what the specific type is.
I would say: why not. A list of objects, in which form you want it is totally legit. I personally don't want the framework to tell me what to do. It is fine to do suggestions, but prevent this code? No.
If you want a list of things that are neither the same type, nor share a base class, nor share an interface, then you need List<Object>.
You very rarely need this.
But if you pursue the thought that List<Object> should be disallowed because it encourages unnecessary and dangerous downcasts, and anyway with generics you can just specify the types actually can handle, shouldn't you then go all the way and disallow the use of Object entirely?