stack collection missing shift and unshift in C# 2.0 - c#

Bizarrely the stack collection seems to be missing the rather basic shift and unshift methods* and I'm working in 2.0 so I can't just extend them.
Is there any reasonable technique or alternative collection class to get these methods available? I need push and pop as well.
Edit: looks like the collection I want is indeed a deque which is happily not native to C# :(
Can't use third party libraries at this time so I'll be going with the clunky LinkedList (I say clunky because reading and removing are two operations where shift would be one) but I think I'd recommend the PowerCollections approach to anyone who could use it. Or better yet, upgrading to extension methods.
sigh
* Apologies, I didn't realise these were uncommon terms, I thought I just didn't know where to find them in the API. For reference:
shift = remove first element
unshift = insert element at beginning of collection

I would say use a LinkedList<T>. It has methods for adding and removing from the front, as well as adding and removing from the back. I've never heard of shifting and unshifting, but I'm assuming that's what it means.

Never heard of shift/unshift in a stack. The Stack class does provide Pop, Peek, and Push though.

You are using the wrong class if you want a shift/unshift method. A stack is a Last-In First-Out (LIFO) data structure.
If you want shift/unshift without pop and push, use a Queue. If you want both, I recommend using Deque from the PowerCollections library

You can fake extension methods as long as you are using C# 3.0 targeting 2.0.
Can you describe what the shift/unshift operations are?

By definition Stack class represents a way of managing elements in a collection using the Last In First Out (LIFO) technique for adding and removing elements. LIFO simply means that the last element added to a collection will automatically be the first one removed.
The functionality you want from it is something custom, but easily can be achieved in following way
public class MyStack<T>:Stack<T>{
public void Shift(T item){
// load stack into internal ordered list
// clear stack content
// insert into internal list at desired location
// populate stack with content from internal list
}
public void Unshift(T item){
// load stack into internal ordered list
// clear stack content
// insert into internal list at desired location
// populate stack with content from internal list
}
}
and seems this it-s all :)

This is not exactly the best, but it comes close to being a Javascript array with shift/unshift and push/pop. Its does not hide the inner workings, and you can index any item you want. I has the basic functionality though.
public class JSList<T> : List<T>
{
public JSList() : base() {}
/// <summary>
/// this the add item to the start of the list
/// </summary>
/// <param name="v"></param>
public void Shift(T v)
{
this.Insert(0, v);
}
/// <summary>
/// remove item at the start of the list
/// </summary>
/// <returns></returns>
public T Unshift()
{
var toreturn = default(T);
if (this.Count > 0)
{
toreturn = this[0];
this.RemoveAt(0);
}
return toreturn;
}
/// <summary>
/// Adds object to end of the list
/// </summary>
/// <param name="v"></param>
public void Push(T v)
{
this.Add(v);
}
/// <summary>
/// removes an item at the end of the list
/// </summary>
/// <returns></returns>
public T Pop()
{
var toreturn = default(T);
if (this.Count > 0)
{
toreturn = this[this.Count - 1];
this.RemoveAt(this.Count - 1);
}
return toreturn;
}
public T Peek()
{
return this[this.Count - 1];
}
}

Shift ==> Stack.Pop
Unshift ==> Stack.Push
Unshift doesn't return the number of elements in the Stack, you have the Stack.Count property for that.
Also, there's Stack.Peek, to get the first element without removing it.
Stack<T> class

Related

Why does ImmutableArray.Create copy an existing immutable array?

I am trying to make a slice of an existing ImmutableArray<T> in a method and thought I could use the construction method Create<T>(ImmutableArray<T> a, int offset, int count)like so:
var arr = ImmutableArray.Create('A', 'B', 'C', 'D');
var bc ImmutableArray.Create(arr, 1, 2);
I was hoping my two ImmutableArrays could share the underlying array here. But
when double checking this I see that the implementation doesn't:
From corefx/../ImmutableArray.cs at github at 15757a8 18 Mar 2017
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array to initialize the array with.
/// The selected array segment may be copied into a new array.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <remarks>
/// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant
/// tax for copying an array when the new array is a segment of an existing array.
/// </remarks>
[Pure]
public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length)
{
Requires.Range(start >= 0 && start <= items.Length, nameof(start));
Requires.Range(length >= 0 && start + length <= items.Length, nameof(length));
if (length == 0)
{
return Create<T>();
}
if (start == 0 && length == items.Length)
{
return items;
}
var array = new T[length];
Array.Copy(items.array, start, array, 0, length);
return new ImmutableArray<T>(array);
}
Why does it have to make the copy of the underlying items here?
And isn't the documentation for this method misleading/wrong? It says
This overload allows helper methods or custom builder classes to
efficiently avoid paying a redundant tax for copying an array when the
new array is a segment of an existing array.
But the segment case is exactly when it copies, and it only avoids the copy if the desired slice is empty or the whole input array.
Is there another way of accomplishing what I want, short of implementing some kind of ImmutableArraySpan?
I'm going to answer my own question with the aid of the comments:
An ImmutableArray can't represent a slice of the underlying array because it doesn't have the fields for it - and obviously adding 64/128 bits of range fields that are only rarely used would be too wasteful.
So the only possibility is to have a proper Slice/Span struct, and there isn't one at the moment apart from ArraySegment (which can't use ImmutableArray as backing data).
It's probably easy to write an ImmutableArraySegment implementing IReadOnlyList<T> etc so will probably be the solution here.
Regarding the documentation - it's as correct as it can be, it avoids the few copies it can (all, none) and copies otherwise.
There are new APIs with the new Span and ReadonlySpan types which will ship with the magical language and runtime features for low level code (ref returns/locals).The types are actually already shipping as part of the System.Memory nuget package, but until they are integrated there will be no way of using them to solve the problem of slicing an ImmutableArray which requires this method on ImmutableArray (which is in System.Collections.Immutable that doesn't depend on System.Memory types, yet)
public ReadonlySpan<T> Slice(int start, int count)
I'm guessing/hoping such APIs will come once the types are in place.

Determining if a Mono.Cecil.MethodDefinition is refering to the same function as a given EnvDTE.CodeFunction

Context
I've been trying out jbEvain's powerful Mono.Cecil library for just about two weeks now. I've created the following function :
/// <summary>
/// Returns true only if they match.
/// </summary>
private bool CompareMethodDefinitionWithCodeFunction(
EnvDTE.CodeFunction pCodeFunction,
Mono.Cecil.MethodDefinition pMethodDefintion)
{
return pMethodDefintion.Name.Equals(pCodeFunction.Name)
&& pMethodDefintion.Parameters.Count == pCodeFunction.Parameters.Count;
}
Goal
The goal is to determine whether pCodeFunction and pMethodDefinition are refering to the same function definition or not. So far, I am able to compare the functions' names and the number of parameters they have. I am well aware that it's not enough to certify that they really are refering to the same function. I need help on improving my comparison. For instance, I believe one should always compare the parameter types in order to take potential function overrides into account.
Previous attempts
I have tried comparing the parameter types but none of my attempts prevailed. Allow me to demonstrate.
I thought I could compare the types as strings so I added abit of code like so :
/// <summary>
/// Returns true only if they match.
/// </summary>
private bool CompareMethodDefinitionWithCodeFunction(
EnvDTE.CodeFunction pCodeFunction,
Mono.Cecil.MethodDefinition pMethodDefintion)
{
foreach (ParameterDefinition paramDef in pMethodDefintion.Parameters)
{
Debug.WriteLine(paramDef.ParameterType.FullName);
}
foreach (CodeElement ce in pCodeFunction.Parameters)
{
CodeParameter codeParameter = ce as CodeParameter;
Debug.WriteLine(codeParameter.Type.AsFullName);
}
return pMethodDefintion.Name.Equals(pCodeFunction.Name)
&& pMethodDefintion.Parameters.Count == pCodeFunction.Parameters.Count;
}
Given that pCodeFunction was refering to the following VB.Net function at runtime
Public Function SomeFunction(ByVal arg As List(Of String)) As Object
Return New Object()
End Function
I got the following output
System.Collections.Generic.List`1<System.String>
System.Collections.Generic.List(Of System.String)
I would prefer not to mess around with these two output values and try to parse them so that they match because this doesn't seem like a very "reliable" way to compare types. What is be the most reliable way to compare the parameter types?
Bonus Notes
This function must be able to seek a function's definition so long as the source code is either VB or C#.
I am currently using the latest Mono.Cecil build (3.12.1) which you can download here
If you want to use my function and insert it in a test class that you've made, you will need the following imports :
using EnvDTE;
using Mono.Cecil;
I believe, after a few more attemps at comparing them appropriately, that there aren't any "proper" ways available out there to compare these two types of objects.
But, I have found a different solution that implies calculating a function index relative to every other function defined within the class. It can get a tiny bit complicated when we start taking the constructors defined in the IL code in consideration but I still think it's appropriate to post this answer out here since it has been my final solution so far. And to be quite frank, the solution as a whole is quite simple.
Allow me to lay out a simple class for demonstrative purposes :
class Class1
{
public static void Function1(string arg1, string arg2)
{
//business logic
}
public static Object Function2(Object arg1)
{
//business logic
}
public static void Function2(List<string> arg1)
{
//business logic
}
}
Function Index
What is my function index supposed to be? Using my Class1 example, simply put, the function's corresponding indexes would be :
0
1
2
Of course, the said function index isn't some property that comes with EnvDTE. I will have to calculate it myself. To implement it, I created a class that contains a EnvDTE.CodeFunction property as well as an int property (intended for the function index).
public class CodeFunctionWithIndex
{
public CodeFunction CodeFunction { get; set; }
public int Index { get; set; }
}
As for our Mono.Cecil.MethodDefinition's function indexes, since we are looping on them (see main post), we can easily calculate their indexes.
It doesn't simply end here though! There are a few things that I need to mention if you want to use the same approach.
To my limited understanding of what goes on behind Mono.Cecil's convenient library, the list of MethodDefinition we are looping through contains all the functions that were generated in IL code after our dll was compiled. But, the class from which our EnvDTE.CodeFunctions reside isn't compiled.
Does a Mono.Cecil.Type (AKA class) contain as many functions as a EnvDTE.ProjectItem (refering to the class)?
No!
Here is what we will have to consider : the constructor(s). A class may or may not have explicitly defined constuctors. But, a Mono.Cecil.Type (AKA the class object of Mono.Cecil) must contain at least one constructor. And believe me, if you don't explicitly define your own constructor, there will be one in the Mono.Cecil.Type!
Finding out if a constructor is explicitly defined within our EnvDTE.ProjectItem(refering to the class) isn't such a hard task. Well... unless you consider the following code complicated.
private List<CodeFunctionWithIndex> GetExplicitlyDefinedConstructors(vsCMElement pRequestedCodeElementKind, CodeElements pCodeElements)
{
int nbCodeFunction = 0; //calculated function index
List<CodeFunctionWithIndex> constructorList = new List<CodeFunctionWithIndex>();
if (pCodeElements != null)
{
foreach (CodeElement element in pCodeElements)
{
//if current element is a namespace
if (element.Kind == vsCMElement.vsCMElementNamespace)
{
constructorList = GetExplicitlyDefinedConstructors(pRequestedCodeElementKind, ((EnvDTE.CodeNamespace)element).Members);
if (!constructorList.Any())
continue;
return constructorList;
}
//if current element is a class
else if (element.Kind == vsCMElement.vsCMElementClass)
{
nbCodeFunction = 0;
constructorList = GetExplicitlyDefinedConstructors(pRequestedCodeElementKind, ((EnvDTE.CodeClass)element).Members);
if (!constructorList.Any()) //because there might be more than one class defined within the active file
continue;
return constructorList;
}
//if current element's kind equals the requested kind
else if (element.Kind == pRequestedCodeElementKind)
{
nbCodeFunction++;
//if it's a constructor, add its index to the list of constructor indexes
if (((CodeFunction)element).FunctionKind.ToString().Contains(vsCMFunction.vsCMFunctionConstructor.ToString()))
{
constructorList.Add(
new CodeFunctionWithIndex()
{
CodeFunction = ((CodeFunction)element),
Index = nbCodeFunction
});
}
}
}
}
return constructorList;
}
And here is how I am calling this function to find out if I have any explicitly defined constructors :
GetExplicitlyDefinedConstructors(
vsCMElement.vsCMElementFunction,
DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElements)
.Any();
But, if there aren't any constructors defined in it, how can our Mono.Cecil.MethodDefinition's function index match with our EnvDTE.CodeFunction's function index?.
Here is the big idea of my solution (tested) :
In VB.Net, if there is no explicitly defined constructor within the class, the constructor in the IL code will be situated at the beguining of the class (function index 0).
In C#.Net, if there is no explicitly defined constructor within the class, the constructor in the IL code will be situated at the end of the class (last function index).
Here is what my function CompareMethodDefinitionWithCodeFunction proposed in my first post looks like today (yes it's been renamed... I apologize for that):
public MethodDefinition FindMethodDefinition(CodeFunctionWithIndex pCodeFunction, bool pHasAnExplicitlyDefinedCtor)
{
//Get the assembly that should contain the function we seek
//Note : this is done by comparing pCodeFunction's assembly name to every assembly's name (without the extension)
ModuleDefinition assemblyContainingMethod = assemblies
.Where(assem =>
assem.Name.Split(new char[] { '.' }).FirstOrDefault()
.Equals(pCodeFunction.CodeFunction.ProjectItem.ContainingProject.Properties.Item("AssemblyName").Value, StringComparison.CurrentCultureIgnoreCase))
.FirstOrDefault();
//Get the class that should contain the function we seek
//Note : pCodeFunction.Parent.Name is the class name of our pCodeFunction
TypeDefinition classContainingMethod =
assemblyContainingMethod.Types
.Where(cl => cl.Name.Equals(((CodeClass)pCodeFunction.CodeFunction.Parent).Name))
.FirstOrDefault();
//below is what you want to see
bool isCtorAtIndexZero = DTE.ActiveDocument.ProjectItem.Name.EndsWith(".vb");
int functionIndex = 0;
for (int i = 0; i < classContainingMethod.Methods.Count; i++)
{
if (!pHasAnExplicitlyDefinedCtor && isCtorAtIndexZero && i == 0)
continue;
if (functionIndex == pCodeFunction.Index)
return classContainingMethod.Methods[i];
functionIndex++;
}
return null;
}
This code is extracted from a working project.
The assemblies variable is a class property of type List<ModuleDefinition>. By the time this function is called, it will contain the assembly in which the function we seek can be found.
Bear with me as I can only clarify so much. The project is rather big, in my opinion anyways, and it can perform many operations that I need to omit from this post as it is not directly related to the question in the first place.
Hope this helps at least a tiny bit. I apologize for the wall of text.

Essentials C# framework 3.5 book errors in example code

I am reading the book Essentials C# 3.0 for .NET framework 3.5 from Mark Michaelis. Since there are more classes involved I was hoping somebody had worked through the book and maybe had the same problem.
The code in chapter 7 fails(page 300). Listing 7.2 shows how to integrate an interface, I've written all of the code like it says in the book.
I'm getting the error:
'xxxx.ConsoleListControl.DisplayHeader(string[])': not all code path returns a value.
The code in question is:
public static void List(string[] headers, Ilistable[] items)
{
int[] columnWidths = DisplayHeaders(headers);
for (int count = 0; count < items.Length; count++)
{
string[] values = items[count].ColumnValues;
DisplayItemsRow(columnWidths, values);
}
}
/// <summary>
/// Displays the column headers
/// </summary>
/// <returns>returns an array of column widths</returns>
private static int[] DisplayHeaders(string[] headers)
{
}
private static void DisplayItemsRow(int[] columnWidths,string[] values)
{
}
}
The string[] headers arefilled with 4 items (FirstName, LastName, Address, Phone).
I don't know what is causing this problem, or how to fix it. I see DisplayHeaders has no value, and columnwidths also has no value.
I haven't put all of the code here; there are 5 classes and 1 interface. I thought maybe that would be to much and not be needed. If somebody wants all the code I will be happy to put it here.
Turn the page, or read again. I guess you're supposed to write code in the method, as it has a return type but no return statement.
Edit: alright, downloaded the PDF, the book explicitly says above this code listing:
Consider another example
And in the code it says:
private static int[] DisplayHeaders(string[] headers)
{
// ...
}
The // ... part indicates something not interesting to the concept being explained is left out for brevity.
The code is shown to explain what an interface can do (in this case printing a list of any kind of object that implements Ilistable), the static helper methods are irrelevant to this. The code is not meant to be run.
Any method that has a type other than void must return an object of that type. So DisplayHeaders must return an integer array.
private static int[] DisplayHeaders(string[] headers)
private - access modifier; indicates this method can only be called from within the class
static - static modifier; this method does not need an instance to be called
int[] - return type; this is the type of the object that this method will return
DisplayHeaders - method name; this is how you refer to this method
(string[] headers) - parameters; this indicates which arguments you need to pass to the method
We can infer from the method summary that its implementation may look something like this:
/// <summary>
/// Displays the column headers
/// </summary>
/// <returns>returns an array of column widths</returns>
private static int[] DisplayHeaders(string[] headers)
{
// builds a new int array with the same
// number of elements as the string array parameter
int[] widths = new int[headers.Length];
for (int i = 0; i < headers.Length; i++)
{
Console.WriteLine(headers[i]); // displays each header in the Console
widths[i] = headers[i].Length; // populates the array with the string sizes
}
// the return keyword instructs the program to send the variable
// that follows back to the code that called this method
return widths;
}
I would continue reading the chapter. More than likely the author fills in the implementation details of that method later on.
The method DisplayHeaders says it returns an array of integers (int[]) but it is not in fact returning anything. There is quite likely code a little bit later on that fills in the method to do something useful, but in order to make the code compile, it needs to return an array. A simple way to do that would be to change it to
private static int[] DisplayHeaders(string[] headers)
{
return new int[0];
}
This causes it to return an empty array of integers.

which should be used: array vs linked list?

I am planning to implement a bounded queue without using the Queue<T> class. After reading pros and cons of Arrays and LinkedList<T>, I am leaning more towards using Array to implement queue functionality. The collection will be fixed size. I just want to add and remove items from the queue.
something like
public class BoundedQueue<T>
{
private T[] queue;
int queueSize;
public BoundedQueue(int size)
{
this.queueSize = size;
queue = new T[size + 1];
}
}
instead of
public class BoundedQueue<T>
{
private LinkedList<T> queue;
int queueSize;
public BoundedQueue(int size)
{
this.queueSize = size;
queue = new LinkedList<T>();
}
}
I have selected Array because of efficiency and due to the fact that collection is fixed size. Would like to get other opinions on this. Thanks.
Well, it would be a mistake. I'm going to guess your are a former C/C++ programmer, std::list is king. On the surface, it is incredibly frugal with memory, can't make a list possibly more efficient than only allocating the memory you need, right? Yes, LinkedList does that.
But no, it is incredibly incompatible with the way CPU caches work, they really like arrays and hate pointers. Put the garbage collector on top of that, so quite capable of packing memory.
The read-them-and-weep benchmarks are here. Stark.
You should of course use a Queue<T>, but in the question you said that you don't want to use queue and instead implement the queue yourself. You need to consider first your use case for this class. If you want to implement something quickly you can use a LinkedList<T> but for a general purpose library you would want something faster.
You can see how it is implemented in .NET by using .NET Reflector. These are the fields it has:
private T[] _array;
private const int _DefaultCapacity = 4;
private static T[] _emptyArray;
private const int _GrowFactor = 200;
private int _head;
private const int _MinimumGrow = 4;
private const int _ShrinkThreshold = 0x20;
private int _size;
[NonSerialized]
private object _syncRoot;
private int _tail;
private int _version;
As you can see it uses an array. It is also quite complicated with many fields concerned with how the array should be resized. Even if you are implementing a bounded array you would want to allow that the array can be larger than the capacity to avoid constantly moving items in memory.
Regarding thread safety, neither type offers any guarantees. For example in the documentation for LinkedList<T> it says this:
This type is not thread safe. If the LinkedList needs to be accessed by multiple threads, you will need to implement their own synchronization mechanism.
I'm not sure why you'd rule out using a Queue<T> internally, especially considering you're up for using a LinkedList<T> (they're in the same assembly). A Queue<T> would give you the greatest performance and memory usage. Your class could look something like this:
public class BoundedQueue<T>
{
private Queue<T> _queue;
private int _maxSize;
public BoundedQueue(int maxSize)
{
if (maxSize <= 0)
throw new ArgumentOutOfRangeException("maxSize");
_queue = new Queue<T>(maxSize);
_maxSize = maxSize;
}
public int Count
{
get { return _queue.Count; }
}
/// <summary>
/// Adds a new item to the queue and, if the queue is at its
/// maximum capacity, also removes the oldest item
/// </summary>
/// <returns>
/// True if an item was dequeued during this operation;
/// otherwise, false
/// </returns>
public bool EnqueueDequeue(T value, out T dequeued)
{
dequeued = default(T);
bool dequeueOccurred = false;
if (_queue.Count == _maxSize)
{
dequeued = _queue.Dequeue();
dequeueOccurred = true;
}
_queue.Enqueue(value);
return dequeueOccurred;
}
}
But maybe you had a good reason for ruling out the Queue<T> class that I just can't think of?
You can use an array, you just have to keep count of the index of the head element, or move everything down by one each time you add something. Arrays are good for accessing by an index, linked lists are good for next/previous and fast insertion.
for instance, if you have [1,2,3,4,5], and the head is 1, you add 6, you'd drop 5 off the back I guess and put six in its place. 6 would be the new head, but the contents of the array would be [1,2,3,4,6].
So here are the main difference/avantages/disavantages of using both arrays and linked-lists:
Arrays:
- Adding items to arrays can be relatively costly if the insertion is not made at the end (as well as deleting) because all the array elements have to be moved.
- Very efficient if object are added at the end
- Access to the elements is very fast... Simply point to the adress!
LinkedList:
- Adding elements anywhere in the queue is always the same cost in time, and is very fast
- Accessing the elements has to be done with an accessor (iterator).
So your trying to implement a queue... but what kind of queue?
It all depends on what you will do with it.
If your implementing First In First Out (or Last In Last Out) queue (like a stack), you are better off using a Linked-List, since you can always use the same accessor to access the front or back-end of your list.
But if you want a queue and have to constantly access your elements at different places, go for the array!
From what I understood of your task, I would have recommended a Linked List... but you will know best!
This will only be a problem if you start having ALOT of elements in your queue. If you stay below the few thousands, it doesn
hope it helps
How will your bounded queue behave when an element is added beyond its capacity? Will the first item be pushed out like this [1, 2, 3] -> [2, 3, 4] or will the last item be replaced like this [1, 2, 3] -> [1, 2, 4]? If the former, then I'd recommend a LinkedList. If the latter, an array or List<T> is fine. I just thought I'd ask since the behavior of your object will determine the appropriate course of action, and that behavior was never defined as far as I can tell. Maybe everyone but me just already knows exactly what you meant by a "bounded queue", but I didn't want to assume.

C# Create Instance of Color from any supported Format (Win.Forms Properties -> Color)

What is the best way to instantiate a new Color from any supported value, like for example
"FF00FF11" or "Gray" or "234,255,65"? I need to generalize maximum as possible this implementation, but can't find a way to do it.
With System.Reflaction I can get the value for enumerator KnownColor, but how can I distinct this "FF00FF11" from this "Gray"?
Any help will be appreciated.
When we need to do this we used the TypeConverter. The static function I used was:
private static System.ComponentModel.TypeConverter colorConv = System.ComponentModel.TypeDescriptor.GetConverter(System.Drawing.Color.Red);
/// <summary>
/// Parse a string to a Color
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
public static System.Drawing.Color ColorFromString(string txt)
{
try
{
object tmp = colorConv.ConvertFromString(txt);
return (tmp is System.Drawing.Color) ? (System.Drawing.Color)tmp : System.Drawing.Color.Empty;
}
catch
{
// Failed To Parse String
return System.Drawing.Color.Empty;
}
}
This works for two of your cases but fails on the Hex one. You could add some logic to try to parse the Hex one first.
You might want to take a look at System.Drawing.ColorTranslator.FromHtml(string).
I'm not sure it'll help you with your last example ("234,255,65"), however. You might have to try to parse that first (String.Split(), Int32.TryParse(), Color.FromArgb()) and if it fails, use the above.

Categories

Resources