Collection parameter in method/constructor? [closed] - c#

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
When some method/constructor accepts a collection parameter, should the parameter type be used as IEnumerable most of the time ? If so, should the method create a new List (.ToList()) to store the reference in a private variable or in method scoped local variable instead of storing the variable in a IEnumerable type variable?
Please let me know.

should the parameter type be used as IEnumerable most of the time ?
If you really mean IEnumerable<T> then yes. Unless the type needs something richer, then you could use one of the interfaces that extend IEnumerable<T>.
You should avoid the non-generic interfaces and collections (namespace System.Collections) in favour of generic ones (namespace System.Collections.Generic).
If so, should the method create a new List (.ToList()) to store the reference in a private variable or in method scoped local variable instead of storing the variable in a IEnumerable type variable?
Possibly yes.
The answer depends on the semantics of your type. If defined as holding a reference to the collection then don't copy it (eg. multiple ContactPerson in an Organisation may all share the list of Interaction with that organisation). In other cases where the new object will own the collection then it should make a copy.

I would say you should use it in a way, that makes you sure you're iterating over the collection only once.
So if you're just using simple foreach IEnumerable is OK, but if you'd like to make more complex things you should store it locally (using ToList(), ToArray() or similar) and than use that local variable instead of iterating over source collection over and over.

If you're going to use only for Read - use IEnumerable, if you want to update the collection, by Add, Remove elements, you should cast to a collection type which allows you to do these actions

Related

Does ImmutableList have AsReadOnly like method? [closed]

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 6 years ago.
Improve this question
AsReadOnly() is a convenient method to get a read-only image (not expensive compared to immutable collections' copies) of a collection. I am wondering if ImmutableList has AsReadOnly like method? If no, any easy way to implement similarly?
Immutable collections are inherently read-only. You can easily check in the documentation that ImmutableList<T> already implements IReadOnlyList<T> and IReadOnlyCollection<T> interfaces.
Memory is not allocated when you access elements from immutable collection. On the other hand, when you add an element to some immutable data structure, a new immutable collection is created (and some memory is used). Many immutable collections' implementations do not copy all the data to a new collection but instead share some data from with the old one, so in most cases you should not be too concerned with memory usage/allocation time.
Some collections, e.g. ImmutableHashSet<T>, have a documentation which states that they are optimized in terms of number of memory allocations.
The idea behind sharing some data between immutable collection is not complicated. Wikipedia has an simple example (with a nice diagram) showing how memory can be saved in case of immutable singly-linked lists.
ImmutableList<T> is copied by reference so is perfectly safe to pass around without a performance penalty. Thus there is no need for an AsReadOnly method as it wouldn't make it any easier to copy.

Is it possible to do workaround to pass property by ref? Plus passing by ref incidences [closed]

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
Is it possible to do workaround for Automatic property of Reference Type (Class) to be able passed by Ref?
The only thing I think about is not to use Automatic property: just declare private variable as always and passing it by ref + adding public property aside if I need.
Frankly it looks a bit stupid ( all that bureaucracy needed to bypass it)
My Questions:
1.Why the compiler don't allow automatic property to be pass by ref(like it was a simple data member)?
2.When do we use or should use Ref? I noticed some people saying that using it may occur only in rare scenarios. What are them?
Why the compiler don't allow automatic property to be pass by ref
because it's not a reference - it's a method pair (get/set). The workaround is to create a local variable that hold's the property's value, pass that by reference, and set the property to the updated value:
var temp = myObj.myProperty;
MethodWithRefParam(ref temp);
myObj.MyProperty = temp;
As you said, you could pass the backing property by reference, but only from within that class.
When do we use or should use Ref?
Typically ref (and out, which is a special case of ref) parameters are only used when returning the value is not practical. TryParse is a common framework example. Instead of returning the parsed value, the method returns a bool telling you whether the parse succeeded or not, and "returns" the parsed value in an out parameter.
Using ref with reference types is usually a code smell that could indicate the author doesn't understand how reference types work.
You use automatic properties because it allows you eventually to change how property is implemented without impacting dependent code. There is no special marking of any kind on property that it was implemented as "automatic". Even if you look at IL of the method you will only find that it is a property with backing field.
As result compiler can't make any assumptions if this property is autogenerated and treats all properties as regular ones.

why microsoft allowed list<object> = new list<object>() feature from 2.0? [closed]

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?

Why anonymous types aren't dynamic as the ExpandoObject? [closed]

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 9 years ago.
Improve this question
With dynamic we pretty much have a dynamic pointer, but not exactly a dynamic object. The true dynamic object in C# is the ExpandoObject, but that is a really unknown class for most of people. The expando allows creating and removing members at runtime, much like a hash (similar to JavaScript).
Why the ExpandoObject goodness was implemented in a separate class rather than just being, let's say, implemented as a feature of anonymous types?
Maybe that wouldn't be a good move because the lacking of type-safety? Or maybe due the (DLR) overhead involved?
Because anonymous types have other very important feature - they provide you compile time type safety.
And because dynamic and anonymous types are just different concepts. The first one gives you ability to dispatch object members at runtime, the second lets you create statically typed objects with some base functionality (equality, hashcode, etc) without creating corresponding POCO classes. Why should they be implemented in the same way then?
btw. I use them quite a lot and really rarely needed to use dynamic to deal with them. Are you sure you're using these language features correctly?
Update
I think that's very important part of anonymous types tutorial:
If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Is there any sense in such kind of refactoring? [closed]

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 8 years ago.
Improve this question
Given web service method:
public void FindSomeEntities(int? Id, string param1, int? param2, ...)
Refactored:
public void FindSomeEntities(SelectionParameters selectionParameters)
class SelectionParameters
{
public int? Id;
public string param1;
public int? param2
...
}
Pros:
too many parameters in original web service method reduced to the
only one
if there is need to change we won't have to change the
interface of the method - only the definition of SelectionParameters
Cons:
class SelectionParameters hasn't any business value - it's used only
as helper class and it's used in a single method. As a result we'll
have many methods with 1 parameters and plenty of one-off classes
Actually the interface IS changed, we just push these changes a bit
deeper.
This refactoring is called Introduce Parameter Object. It is likely to be a good idea if the parameters are naturally related to each other, and especially if they're frequently used together as parameter lists to multiple methods.
I'm not sure there is much value in this kind of refactoring because as you say, the number of supporting classes will/could be a pain to maintain and serve no other purpose.
If the parameters have distinct purposes, such as in your example 'ID' then I would think it would be sensible to keep them separate so as to make it easy to identify them and what you want to do with them in the method body.
If however your params are just a collection of values which perform similar/the same functions in the method body, you could look at using the params keyword and defining your method like this:
public void FindSomeEnteties(params object[] theParameters)
It depends whether you want to have to dig through an array to pull out index 0 and treat it as the ID, etc etc, or whether your method simply wants to do the same thing to all the parameters passed.
If there is any reason to believe that the same (sub)set of parameters is shared by other web services, this is reasonable.
Whether you do it not, you have a defacto struct as the argument list anyway. This observation is realized in our PARLANSE programming language, which has always a single argument to function, named '?' (sort of like "self" in OO ). That argument has a type; it can be a scalar or complex variable (int or string), or it can be struct. Normally one defines a struct by a struct declaration; in PARLANSE, writing what appears to be multiple arguments implicitly defines a struct. In those cases where the argument list is passed to a child function, one can simply call that child function on '?' and the entire argument list is passed.

Categories