I making a hashtable(not really important I think), I wanna print out all my elements from my variabel linked list, the insertionOrder(it holds strings, but doesn't matter), I have to do like this, in my method i want to return insertionOrder, but not sure how to do that so the method get all the elements, and in my class Program I wanna print out the insertionOrder, I can't find a solution, thanks! Why I have to do like this? my teacher want it like this. I just wonder if you know a solution. Thanks!
class Hashtable
{
private LinkedList<object> insertionOrder = new LinkedList<object>();
.
.
public LinkedList<object> GetInsertionOrder()
{
return insertionOrder;
}
}
class Program
{
static void Main(string[] args)
{
Hashtable hT= new Hashtable(8);
Console.Writeline("The elements: " + hT.insertionOrder());
}
}
A few things;
insertionOrder is declared outside the main class, as private, so you're not going to be able to get to it from Main().
insertionOrder has absolutely nothing to do with the Hashtable. I'm surprised your IDE isn't throwing up an error at the hT.insertionOrder() call, since it's not valid.
Try something like this.
class Program
{
private LinkedList<object> insertionOrder = new LinkedList<object>();
static void Main(string[] args)
{
int count = 1;
foreach (object o in insertionOrder)
{
Console.Writeline("The Element(" + count + "): " + o.ToString());
count++;
}
}
}
Related
I have been reading some C# interview questions and found a permutation of a popular one about delegates the code of which puzzles me.
The question was:
Predict the output of the code below.
delegate void Iterator();
static void Main(string[] args)
{
List<Iterator> iterators = new List<Iterator>();
for (int i = 0; i < 15; i++)
{
iterators.Add(delegate { Console.WriteLine(i); });
}
foreach (var iterator in iterators)
{
iterator();
}
Console.Read();
}
The normal version of this question I've seen declares the i variable before the for loop, thus making it method-wide and from there it's easy to see why the output is "15" 15 times.
However when I debugged the code the i variable is out of scope in the foreach loop and does not exist, anymore. Yet, when I step into the iterator() method it exists for the Console.WriteLine(i) line.
This I cannot understand.
The compiler translates your code to the following code, this is why i variable is not out of scope.
private delegate void Iterator();
[CompilerGenerated]
private sealed class CompGenCls
{
public int i;
internal void CompGenFunc()
{
Console.WriteLine(i);
}
}
private static void Main(string[] args)
{
List<Iterator> iterators = new List<Iterator>();
CompGenCls obj = new CompGenCls();
obj.i = 0;
for (; obj.i < 15; obj.i++)
{
iterators.Add(obj.CompGenFunc);
}
foreach (Iterator item in iterators)
{
item();
}
Console.Read();
}
To put it very simply, closures allow you to encapsulate some
behaviour, pass it around like any other object, and still have access
to the context in which they were first declared. This allows you to
separate out control structures, logical operators etc from the
details of how they're going to be used. The ability to access the
original context is what separates closures from normal objects,
although closure implementations typically achieve this using normal
objects and compiler trickery.
In your example you've only actually declared a single i variable -
so that same i variable is captured by all the Action instances. The
result is the number 15 being printed on every line. o "fix" the code
to make it display the output most people would expect (i.e. 0 to 14)
we need to introduce an extra variable inside the loop:
delegate void Iterator();
static void Main(string[] args)
{
List<Iterator> iterators = new List<Iterator>();
for (int i = 0; i < 15; i++)
{
int copy = i;
iterators.Add(delegate { Console.WriteLine(copy); });
}
foreach (var iterator in iterators)
{
iterator();
}
Console.Read();
}
Each time we go through the loop we're said to get a different
instance of the copy variable - each Action captures a different
variable. This makes perfect sense if you look at what the compiler's
actually doing behind the scenes, but initially it flies in the face
of the intuition of most developers (including me).
via
I am a beginner developer, and would very much appreciate if you can help me figure out the problem which is in my code. The code is particularly confusing, mainly because it derives from a framework. The comments should be able to somewhat allow us to understand.
// Create an IBindable List
public static List<IBindable> KyzerBindables = new List<IBindable>();
// Attach elements to a list, for better control over all of them
internal static void AttachBindablesToList(IReadOnlyList<Drawable> children)
{
// For all the children classes located in Drawable list
for (int i = 0; i < children.Count; i++) // children.Count returns 4
{
// For all of the SettingsSubsection which are present in the Drawable array
for (int l = 0; l < (children[i] as SettingsSubsection).Children.Count; l++) // (children[i] as Subsection).Children.Count returns 0.
{
// Get a specific element
var element = (children[i] as SettingsSubsection).Children[l];
// if is a SettingsCheckbox
if (element.GetType() == typeof(SettingsCheckbox))
KyzerBindables.Add((element as SettingsCheckbox).Bindable);
}
}
}
// in another class
public class KyzerSection: SettingsSection
{
public KyzerSection()
{
Children = new Drawable[]
{
new KyzerMiscellaneous(),
};
...AttachElementsToList(Children);
}
}
public class KyzerMiscellaneous: SettingsSubsection
{
[BackgroundDependencyLoader] // Calls load, framework thing.
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Something here",
Bindable = new BindableBool(false),
}
};
}
}
My problem is, the second for loop does not even initiate for the AttachBindablesToList. For whatever particular reason, it isn't recieving a count. I am uncertain of what I am doing wrong.
Edit:
If, in any way, the GitHub repository issue can clear some issues up, please feel free to navigate there and check the commit which contains these changes. https://github.com/Frontear/osuKyzer/issues/3
After reviewing your github repository, I believe the issue is caused at:
private void load(params here)
The above is not being called at the time of AttachBindablesToList. This results in an empty
(children[i] as SettingsSubsection).Children.Count
The best option is to create an empty instantiation method
public KyzerMiscellaneous() { /* create Drawable elements */ }
// then
[BackgroundDependancyLoader]
private void load(params here) { /* doSomething */ }
This will allow access to the children list since it has been initialized before, which therefore allows the second loop to correctly function, and pushes IBindables to your list.
I am just a beginner in the world of programming, thus I have a simple question. Is it possible to randomly execute functions? If so, how would you do it? It is just a curiosity based on a thread I've read in another forum. Basically, the discussion was on how to generate random events for a game, and they commented about a "hack" used in some languages (especially AS3). The hack is to treat functions as variables. Example:
//Make an array of the functions
public function makeEarthquake():void{}
public function causePlague():void{}
public function spaceZombieAttack():void{}
//select at random
var selection:uint = Math.random() * eventArrray.length;
//Call it
eventArray[selection]();
I hope this is clear. I will be happy with any answer that can explain how to randomly call methods. Thank you.
EDIT: Thank you guys, all the answers were helpful!!!
It's certainly possible. A direct way is to have a list or array of delegates:
In C# it looks like this: (In a basic console app)
class Program
{
// Create the functions:
static void Beep()
{
Console.Beep();
}
static void SayHello()
{
Console.WriteLine("Hello!");
}
// Create the function delegate:
private delegate void RandomFunction();
static void Main(string[] args)
{
// Create a list of these delegates:
List<RandomFunction> functions = new List<RandomFunction>();
// Add the functions to the list:
functions.Add(Beep);
functions.Add(SayHello);
// Make our randomizer:
Random rand = new Random();
// Call one:
functions[rand.Next(0, 2)](); // Random number either 0 or 1
// This is just here to stop the program
// from closing straight away should it say "Hello"
Console.ReadKey();
}
}
Getting these functions to have varying numbers of parameters takes a bit more effort, though.
You can have a List<Action> and randomly select from it.
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
actions.Add(() => Program.MakeEarthquake());
actions.Add(() => Program.CausePlague());
actions.Add(() => Program.SpaceZombieAttack());
Random random = new Random();
int selectedAction = random.Next(0, actions.Count());
actions[selectedAction].Invoke();
}
static void MakeEarthquake()
{
Console.WriteLine("Earthquake");
}
static void CausePlague()
{
Console.WriteLine("Plague");
}
static void SpaceZombieAttack()
{
Console.WriteLine("Zombie attack");
}
}
You can create list of actions then choosing one the items inside the list randomly like below code
List<Action> actions = new List<Action>();
actions.Add(() => makeEarthquake());
actions.Add(() => causePlague());
actions.Add(() => spaceZombieAttack());
var random=new Random();
int rndNumber = random.Next(actions.Count);
actions[rndNumber].Invoke();
Why don't you pick a random number like usual, then use that number within a common function which in turn calls a function based on what you got?
public void DoRandomThing()
{
switch(new Random().Next(1,4))
{
case 1:
makeEarthquake();
break;
case 2:
causePlague();
break;
case 3:
spaceZombieAttack();
break;
}
}
I've seen countless posts on how variable capture pulls in variables for the creation of the closure, however they all seem to stop short of specific details and call the whole thing "compiler magic".
I'm looking for a clear-cut explanation of:
How local variables are actually captured.
The difference (if any) between capturing value types vs. reference types.
And whether there is any boxing occurring with respect to value types.
My preference would be for an answer in terms of values and pointers (closer to the heart of what happens internally), though I will accept a clear answer involving values and references as well.
Is tricky. Will come onto it in a minute.
There's no difference - in both cases, it's the variable itself which is captured.
Nope, no boxing occurs.
It's probably easiest to demonstrate how the capturing works via an example...
Here's some code using a lambda expression which captures a single variable:
using System;
class Test
{
static void Main()
{
Action action = CreateShowAndIncrementAction();
action();
action();
}
static Action CreateShowAndIncrementAction()
{
Random rng = new Random();
int counter = rng.Next(10);
Console.WriteLine("Initial value for counter: {0}", counter);
return () =>
{
Console.WriteLine(counter);
counter++;
};
}
}
Now here's what the compiler's doing for you - except that it would use "unspeakable" names which couldn't really occur in C#.
using System;
class Test
{
static void Main()
{
Action action = CreateShowAndIncrementAction();
action();
action();
}
static Action CreateShowAndIncrementAction()
{
ActionHelper helper = new ActionHelper();
Random rng = new Random();
helper.counter = rng.Next(10);
Console.WriteLine("Initial value for counter: {0}", helper.counter);
// Converts method group to a delegate, whose target will be a
// reference to the instance of ActionHelper
return helper.DoAction;
}
class ActionHelper
{
// Just for simplicity, make it public. I don't know if the
// C# compiler really does.
public int counter;
public void DoAction()
{
Console.WriteLine(counter);
counter++;
}
}
}
If you capture variables declared in a loop, you'd end up with a new instance of ActionHelper for each iteration of the loop - so you'd effectively capture different "instances" of the variables.
It gets more complicated when you capture variables from different scopes... let me know if you really want that sort of level of detail, or you could just write some code, decompile it in Reflector and follow it through :)
Note how:
There's no boxing involved
There are no pointers involved, or any other unsafe code
EDIT: Here's an example of two delegates sharing a variable. One delegate shows the current value of counter, the other increments it:
using System;
class Program
{
static void Main(string[] args)
{
var tuple = CreateShowAndIncrementActions();
var show = tuple.Item1;
var increment = tuple.Item2;
show(); // Prints 0
show(); // Still prints 0
increment();
show(); // Now prints 1
}
static Tuple<Action, Action> CreateShowAndIncrementActions()
{
int counter = 0;
Action show = () => { Console.WriteLine(counter); };
Action increment = () => { counter++; };
return Tuple.Create(show, increment);
}
}
... and the expansion:
using System;
class Program
{
static void Main(string[] args)
{
var tuple = CreateShowAndIncrementActions();
var show = tuple.Item1;
var increment = tuple.Item2;
show(); // Prints 0
show(); // Still prints 0
increment();
show(); // Now prints 1
}
static Tuple<Action, Action> CreateShowAndIncrementActions()
{
ActionHelper helper = new ActionHelper();
helper.counter = 0;
Action show = helper.Show;
Action increment = helper.Increment;
return Tuple.Create(show, increment);
}
class ActionHelper
{
public int counter;
public void Show()
{
Console.WriteLine(counter);
}
public void Increment()
{
counter++;
}
}
}
I am generally not very fond of refactoring tools. No need to get into details. Still, I occasionally try out new versions. Here is what I was trying to do while evaluating resharper 4.5 :
I needed to replace all usages of a method with a wrapper method (to be created) but I could not. I usually suck at noticing an obvious feature, is this the case? If resharper does not have this feature, do you know such tools?
Edit 2: Sample has been improved to include instance method calls.
Edit:
Here is a simple case to play.
static void Main(string[] args)
{
while(true)
{
if (Console.ReadKey().Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
Console.Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Console.Beep(250, 150);
return false;
}
return true;
}
What I need is something like: (Edit2: added an instance sample)
private static StringBuilder _builder = new StringBuilder();
static void Main(string[] args)
{
while(true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
_builder.Append(" (").Append(key.KeyChar).Append(") ");
Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Beep(250, 150);
_builder.Append('#');
return false;
}
return true;
}
static void Beep(int frequency, int duration)
{
// finally cursor ends up here
Console.Beep(250, 50);
}
Console.Beep calls are refactored. Next lets refactor StringBuilder.Append(char) :
class Program
{
private static StringBuilder _builder = new StringBuilder();
static void Main(string[] args)
{
while(true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
_builder.Append(" (").AppendUpper(key.KeyChar).Append(") ");
Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Beep(250, 150);
_builder.AppendUpper('n');
return false;
}
return true;
}
static void Beep(int frequency, int duration)
{
// finally cursor ends up here
Console.Beep(250, 50);
}
}
static class StringBuilderExtensions
{
public static StringBuilder AppendUpper(this StringBuilder builder, char c)
{
return builder.Append(char.ToUpper(c));
}
}
Selecting from usages and maybe omitting common parameters (such as 250 above) or common instance parameters for non-extension statics shall make this feature more valuable. Hopefully, this clears up the question.
ReSharper doesn't have this as a single refactoring. I might do it as follows:
Select the contents of the method to be wrapped, and use Extract Method to create a new private method from the contents.
The original method is now a trivial wrapper around "itself". Rename it if you like, or manipulate it as you like (make it static, move to a different class, surround with try/catch, whatever).
EDIT:
Based on your edit, it seems you have an additional problem. Not only is Console.Beep not in the same class, it's not even in your class.
But if you don't mind a little search and replace, then you can put it into your own class, then proceed with the refactoring:
namespace Temporary {
public class Console {
public static void Beep(int x, int y) {System.Console.Beep(x,y);}
}
}
Then do a "Replace in Files" to replace Console.Beep with Temporary.Console.Beep, and proceed as above.
It's not included in any .NET refactoring IIRC, the tool which has such a refactoring is Eclipse, but not for .NET/C#
Assuming the wrapper method will be in the same class you can rename the current method to the name of the new wrapper method (ctrl+R+R in Resharper). This will rename all calls to this method in the solution as well. Then rename the original method back by hand (don't use Resharper or all the calls will get renamed back too) and add the wrapper method.
Based on your edit I think you will be out of luck to get the functionality that you want from any Visual Studio add-in that I've seen (beyond the simple find and replace which will get you some of the way there I guess).
Depending on how much time and effort you are willing to devote to this I'd imagine it's possible to use the DXCore framework and write a plugin that will do this kind of refactoring.
Resharper has a Search and Replace with Pattern feature. It can search and replace on patterns and expressions.
This would refactor all calls to Console.Beep() to your own method. It only replaces the usage if 250 is the first parameter:
However this would replace the usage of Console.Beep() within your own Beep method. You would have to manually replace that one usage.