Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Why doesn't the .net generic type List<T> offer any Clone() function?
Why doesn't it implement IClonable?
The problem with cloning objects and, especially the ICloneable interface, is that the public interface doesn't communicate the intention well.
Namely - will such Clone function of the List<T> clone contained elements as well, or just clone the list and copy the references to contained elements? Shallow copy, which copies the references and only creates the new list would be equivalent to this:
List<T> clone = new List<T>(originalList);
However, if you wanted to force all the contained elements to be cloned as well, then it would be equivalent to this:
List<T> clone = originalList.Select(x => (T)x.Clone()).ToList();
This assumes that the type T is implementing ICloneable. However, even with this solution, exact effects of code execution cannot be told in advance. What does it mean for an element x to clone itself? Will it be a shallow copy (offered by the MemberwiseClone method it inherits form System.Object), or will it be a deep copy. And if deep, what will happen if two objects in the list are referencing the same third object? Will that third object be copied twice or only once? And so on... you can see where this is going.
For all the reasons listed above, cloning facilities are not incorporated in the framework. It is left to custom code to decide what it means to clone an object and then implement custom code for that.
To make a cloneable List type you would do:
public class CloneableList<T> : List<T>, ICloneable
{
public object Clone() {
var clone = new CloneableList<T>();
clone.AddRange(this);
return clone;
}
}
Or this if you want it deeply cloned:
public class DeepCloneableList<T> : List<T>, ICloneable where T : ICloneable
{
public object Clone() {
var clone = new DeepCloneableList<T>();
clone.AddRange(this.Select(x => (T)x.Clone()));
return clone;
}
}
Because List<T> does not inherit from IClonable. If you want to do a clone of a list you could do...
var t = new List<IClonable>();
var newList = t.Select(a=>a.Clone()).ToList();
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 4 years ago.
Improve this question
I'd like to ask if it is possible to add an item to a list of interface?
Example:
I have a list of interface:
List<ITestItem> testList = new List<ITestItem>();
I want to add a new item to that list. But I couldn't find a way to create a new instance from ITestItem.
Besides, there is no class that implements the interface ITestItem.
So, is there anyway to add a new item to ITestItem?
All I want is something like:
List<ITestItem> testList = new List<ITestItem>();
testList.Add(new ITestItem());
Thank you in advanced.
Note: my question is to ask if it is possible. If no, it's OK for me.
You can't create an instance of an interface, but you can create an instance of a class that implements an interface.
As long as the object you're adding, is an instance of a class that implements ITestItem it can be added to your List<ITestItem>
Example:
public class SomeListItem : IListItem
{
}
var item = new SomeListItem();
testList.Add(item);
Alternatively (and possibly more likely) there will be a class that already implements IListItem somewhere within the code that has IlistItem
No you cannot instantiate an interface. You need to create a class that implements that interface.
No, an interface is not instantiable. You need a class that implement your interface, and instantiate an instance of this class that you can then add to your list.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
.NET has a bunch of sorted collections. However, only implementations were added, such as:
SortedList<TKey, TValue>
SortedDictionary<TKey, TValue>
SortedSet<T>
However, none of these implement a "matching" interface, they only implement IList<T>, IDictionary<Tkey, TValue> and ISet<T>.
In my opinion, the fact that a collection is sorted is something that you might want to communicate to your consumers without further specifying a specific implementation. Furthermore, I don't think that adding such interfaces would be complicated.
Am I thinking about this the wrong way, perhaps?
I will say that it is "because there is no way to convene how the SortedXXX<> is sorted". The IComparer<> interface isn't self-describing.
If I told you "this collection is sorted", would this information be important for you? Perhaps it is sorted by the SHA256 of its keys... It is still sorted, but is sorted by something that no human person would consider an "ordering"? The only guarantee given by this "sorted" would be that two runs of GetEnumerable() would return the items in the same ordering (so the GetEnumerable() would be "stable"). HashSet<> doesn't even guarantee it probably.
To give an example:
var ss1 = new SortedSet<string>(StringComparer.CurrentCultureIgnoreCase);
A "classical" SortedSet<>, ordered by the CurrentCultureIgnoreCase. It is "sorted" to something a human will recognize.
var ss2 = new SortedSet<string>(Comparer<string>.Create((p, q) => p.GetHashCode().CompareTo(q.GetHashCode())));
A SortedSet<> ordered by the GetHashCode() of its elements. No human would "appreciate" it... But it is still sorted :-)
If you then proposed "then the interface could simply implement a Comparator getter to return which comparator is used" (ignoring that the comparators aren't self-describing), note that:
var cmp1 = StringComparer.CurrentCultureIgnoreCase; // instance of System.CultureAwareComparer
var cmp2 = StringComparer.CurrentCultureIgnoreCase; // instance of System.CultureAwareComparer
bool same = object.ReferenceEquals(cmp1, cmp2); // false
and then
var cmp3 = StringComparer.CurrentCulture; // instance of System.CultureAwareComparer
Woops... It is even difficult to distinguish between StringComparer.CurrentCulture/StringComparer.CurrentCultureIgnoreCase.
In the end my point is:
if you knew a collection is sorted, what could you do with that information without knowing if its sorting is the one you need?
In lieu of someone who can give you a concrete answer I offer up an opinion:
The fact that a collection is sorted is an implementation detail, and as such there is nothing of interest to put on a suggested interface such as ISortedDictionary.
There is an interface for SortedDictionary<T,T> - it's IDictionary<T,T>.
Also, SortedSet<T> implements ISet<T>.
That illustrates a reason why there aren't "sorted" interfaces. The interface defines how you interact with the class, not its implementation. What a consumer of that class needs to know is that it behaves as a dictionary. It doesn't need to know that anything gets sorted. If it does need to know that then it shouldn't depend on the interface. It should depend on the class.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
public class MyTokenStore: ITokenStore
{
public IToken CreateRequestToken(IOAuthContext context)
{
...some code here...
}
public IToken CreateAccessToken(IOAuthContext context)
{
...some code here...
}
}
Which one of below is better ?
Option1 - ITokenStore x = new MyTokenStore(); OR
Option2 - MyTokenStore x = new MyTokenStore()
What are the advanatges of both ?
Can I restrict user from using Option 2 ?
Users decide for themselves which version they use. The advantage of option 1 is that the user can really instantiate any class that implements the interface. Say you have a helper class that contains a method
DoSomethingVeryUseful(ITokenStore store)
then again that method becomes more useful because it can be called with any object that implements said interface.
The advantage of using option 2 is that your class may contain methods that are not part of the interface, and thus those methods can only be used with option 2.
There is no general good response to this, as it fully depends on you concrete case.
ITokenStore x = new MyTokenStore()
mades a "slice" over concrete MyTokenStore instance where not all members are inside ITokenStore, so you missing access to some additional information that may be present in MyTokenStore and is not present in ITokenStore.
On other hand you create an abstraction layer, so gain a flexibility.
The purpose of an interface is to expose functionality that is common to all implementer's and is agnostic of the concrete implementation. If you are trying to pass around multiple concrete objects to a consumer that needs to access an interface method, then cast it as an interface.
However, if you need a specific member on the concrete implementation, use that.
This is not which is better question but more what are you going to do with it ? Somethings to consider
Are you going to have multiple objects implement the interface ?
Are you going to be doing unit testing ?
Are you going to be doing any in Dependency Injection ?
If you can answer yes to at least one of the questions the using a interface is a good idea but if your using a interface just to use a interface you might want to rethink the solution
My suggestion is the below option. Instead creating "new" object, we can go with contructor injection.
public class MyTokenStore{
private readonly ITokenStore;
public MyTokenStore{ITokenStore TokenService)
{
this.TokenStore=TokenService;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If a class instantiated it will create an object.Memory will allocated to the instance. What happens if Interface intstantiated? Does interface has constructors? Does it create an interface object.does it alllocate memory to interface object
interface IInteface {}
class Test : IInterface{}
IInterface ex1 = new Test();
what above line will create ?
Interfaces are abstract concepts that cannot be instantiated. They serve to define a contract for implementing classes to fulfill.
Then, you can create instances of concrete classes implementing the interface (usually with new), and use an interface reference to point to that instance.
Interfaces have no constructors and can't be created by themselves.
Assigning an object to variable (including variable of interface type) does not create new object, it is just another reference to the same object.
class DerivedWithInterface: Base, IEnumerable {}
Now you can create instances of DerivedWithInterface class and assign to variable of any of base classes/interfaces, but only new will create an object:
DerivedWithInterface item = new DerivedWithInterface();
IEnumerable asEnumerable = item; // asEnumerable is the same object as create before
Base asBase = item;
Now you can do casts back to original object and there still will be exactly one (or as many as you've newed up):
IEnumerable asEnumerableItem = new DerivedWithInterface();
DerivedWithInterface itemViaCast = (DerivedWithInterface)asEnumerableItem;
both asEnumerableItem and itemViaCast refer to the same single instance of and object of type asEnumerableItem
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 8 years ago.
Improve this question
I came across this situation where List has no type specified after it in <>:
List someVar = new List();
However when I try this in Visual Studio I get an error. What is the reason for VS not letting me declare List this way?
Let me show you where I saw it:
public override IEnumerable SomeMethod()
{
List someVar= new List();
// more code
return someVar;
}
P.S After contacting the owner of the project it turned out Wordpress striped out the tags <> after List and IEnumerable, so it actually should be List<SomeClass> and IEnumerable<SomeClass>
public override IEnumerable<SomeClass> SomeMethod()
{
List<SomeClass> someVar= new List<SomeClass>();
// more code
return someVar;
}
There is not an inbuilt class called List. There is ArrayList, but: click on List and press f12. This will show you where it is declared. There are two options:
a class called List that is nothing whatsoever to do with List<T> has been declared in the local project; for example:
class List { ...} // here we go; a class called List
a using alias (at the top of the file) has been used to spoof List as a name; for example:
using List = System.Collections.Hashtable;
or
using List = System.Collections.Generic.List<int>;
You get an error because the List class does not exist in the .NET Framework. If you want to use a non-generic list that can hold any type of object, use ArrayList.
I don't recognise it (I thought it was ArrayList before List<T> arrived?). Either way it would be an older class invented before generics was implemented. I'd use List<object>.