Jump to content

C# accessing function of class in arraylist

Guest

I'm programing something in unity and I am not sure of how to access the functions of objects in an ArrayList.
Psuedo Code:

If I press numberpad enter (Or KeypadEnter when using proper C# syntax) tell all objects in ArrayList to execute "ExecuteCommand" function.



C# code example (This isn't my exact code. It has too much other stuff people may get distracted on.)

First Class

public class ControlClass : MonoBehaviour {
	ArrayList controlledObjects = new ArrayList(); //The amount of objects in this array will change, However they will all be the same object. 
	ControlledObject cO;

	void Update () {
		if (input.GetKeyDown(KeyCode.KeypadEnter)){
			cO.ExecuteCommand;//This is the line that doesn't seem to work. 
          	controlledObjects.executeCommand;//Even if I try it like this.
		}
	}

	void AddObject () { // this function can be ignored. It is just how I add objects to the array. I felt it was important so people could 									better understand
		Raycast hit;
      	if (Physics.Raycast(transform.position, transform.forward, out hit, 50f))
        {
        if (hit.transform.tag == "Controllable Object"){
                cO.Add(hit.collider.GetComponent<ControlledObject>());
            }
        }
	}
}

 

Second Class

public class ControlledObject : MonoBehavior {
	void ExecuteCommand () {
		print("Command Executed."); // There is code in my program that is suppossed to execute that doesn't. Not even my print statements for debugging. 
	}
}

And that's basically my problem. Any help would be greatly appreciated. I was able to accomplish my goals with 1 object (Using GameObject instead of ArrayList) but it was limiting in how many commands could be executed with a single key stroke.

 

Link to comment
Share on other sites

Link to post
Share on other sites

ArrayList is a generic type, meaning you need to define what class the arraylist is actually referencing. Do this by setting ArrayList<ControlledObject> controlledObjects = new ArrayList<>();

 

This should allow you to call the function ExecuteCommand on each object stored in the ArrayList, but as it is right now you have to iterate through the items in your ArrayList and call each individually, using a for loop and using the ArrayList get(int) method can do this. Also you always need to call functions and methods with () and any parameters in them that the function needs, so ExecuteCommand isn't a proper function call, it is ExecuteCommand().

 

Mind you this is all general C#, as Ive never worked with it in unity before, so if my answer is wrong I apologize.

Link to comment
Share on other sites

Link to post
Share on other sites

This seems to be either a casting issue (namely casting the object which is returned from the ArrayList) or trying on an undefined item. I would suggest an List<ControlledObject> if thery are all the sme

Link to comment
Share on other sites

Link to post
Share on other sites

41 minutes ago, ItsMTC said:

ArrayList is a generic type, meaning you need to define what class the arraylist is actually referencing. Do this by setting ArrayList<ControlledObject> controlledObjects = new ArrayList<>();

 

This should allow you to call the function ExecuteCommand on each object stored in the ArrayList, but as it is right now you have to iterate through the items in your ArrayList and call each individually, using a for loop and using the ArrayList get(int) method can do this. Also you always need to call functions and methods with () and any parameters in them that the function needs, so ExecuteCommand isn't a proper function call, it is ExecuteCommand().

 

Mind you this is all general C#, as Ive never worked with it in unity before, so if my answer is wrong I apologize.

Generally Speaking a lot of Unity Programming is basic C#, just with Unity's API and whatnot so you can program things easier.

Unity wouldn't accept Do this by setting ArrayList<ControlledObject> controlledObjects = new ArrayList<>(); because

Quote

Error 1 The non-generic type 'System.Collections.ArrayList' cannot be used with type arguments c:\users\public\documents\unity projects\new unity project\assets\usedassets\scripts\player\sendorder.cs 14 5 Assembly-CSharp

I'm not sure what that means. It is referencing what is between the <Things between these brackets.> There is a second error marking the second item <between these brackets> as well.

I googled the error and came across this :
Stack OverFlow
It mentioned what @nokel81 recommended about using Systems.Collections.Generic; (Link to Microsoft documentation.)
I implemented that and it removed the error about arguments. However I still couldn't reference the function.
The stack overflow link(ed above) mentions that. The user recommends using
 

var al = (ArrayList)parameters
var l = (System.Collections.IList)parameters

but I've never seen var used in C# before. Only in JavaScript (used for making variables and functions.)
On Microsoft's documentation website regarding var it doesn't seem to explain what I need.

Thanks to the both of you for helping. I kinda understand what you mean @nokel81 by a casting issue in how I may not be able to use an object's function that way.

As for @ItsMTC a for loop may be what I needed. I couldn't figure out a way to do it, but I'm testing a foreach loop.
Unfortunately I cannot find a way to get this to work as it appears foreach loops don't present numbers of any kind like a normal for loop.

This is what I have but it seems to have problems with syntax.
 

foreach (ControlledClass element in controlledObjects) {
                cO = controlledObjects;
                cO.ExecuteCommand;
            }



Sorry for such a lengthy reply. I'm doing my best to document everything as I do it. Just in case someone 12 years from now googles my problem, they won't have any missing pieces like I have.

EDIT:
wow.. I worked on that post for 37 minutes... You future person plz be satisfied with my legacy.

Link to comment
Share on other sites

Link to post
Share on other sites

So the foreach should read like this:

foreach (ControlledObject element in ControlledObjects) {
  element.ExecuteCommand();
}

What the stack over flow posting means is that the ArrayList container object stores object references (or pointers, I don't quite know how C#'s memory management works) instead of `<T>` pointers if you did `System.Collections.List<T>`.

 

The above works because foreach will cast the element to the given type at run time or throw an InvalidCastException. The above loop is equivalent to:

foreach (var __o in ControlledObjects) {
  (ControlledObjet)__o.ExecuteCommand();
}

I know Microsoft does not have very much about the `var` keyword. It is used like in javascript it infer types. Technically it is the standard for helper variables but I don't like using it since it is less descriptive and you loose some the controls.

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, nokel81 said:

you loose some the controls.

What do you mean by that exactly?

 

Honestly I don't know why you are using a non generic container for this. Casting your objects is a very bad code smell and you should completely avoid doing so; you should be using a generic container instead. You can even do away with the for/foreach loop by using LINQ if you have a simple enough scenario (and you should have a simple scenario).

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

@Nuluvius I me that using "var" instead of type int or Int16/Int32, I would say that the program looses some of the memory control

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, nokel81 said:

@Nuluvius I me that using "var" instead of type int or Int16/Int32, I would say that the program looses some of the memory control

Yes your right in very specific situations that is true. However I don't agree with you outside of those since I think that it's much more readable/descriptive! Indeed it's predominantly been the style that I have encountered - yet ultimately it's always going to be a subjective argument.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Nuluvius said:

Yes your right in very specific situations that is true. However I don't agree with you outside of those since I think that it's much more readable/descriptive! Indeed it's predominantly been the style that I have encountered - yet ultimately it's always going to be a subjective argument.

I'd imagine it to be like 4 spaces vs tabs or

if {

}

vs

if

{

}

 

4 hours ago, nokel81 said:

So the foreach should read like this:


foreach (ControlledObject element in ControlledObjects) {
  element.ExecuteCommand();
}

 

That was it! Thank you. I was looking at it for a little while because I forgot the function needed an argument (or specific variable) passed through it. A minor other bug I knew the problem of and it worked!

I think this forum taught me more about programming than and college professor in a class.

 

2 hours ago, Nuluvius said:

What do you mean by that exactly?

 

Honestly I don't know why you are using a non generic container for this. Casting your objects is a very bad code smell and you should completely avoid doing so; you should be using a generic container instead. You can even do away with the for/foreach loop by using LINQ if you have a simple enough scenario (and you should have a simple scenario).

I don't know what you mean by using a non-generic container. My knowledge of how all the functions interact is limited. I just learned about Lists (in opposition to ArrayLists) just last night. That appears to be a Generic type.
As for the Casting objects where did I do that, and how can I prevent doing that?

I searched LINQ and found this. A Wikipedia page on Language Integrated Query (Pronounced Link)
My scenario seems to be simple enough.

 

I want to execute the same function on multiple instances of the same object in a specific group of objects.

 

Partway down the page it starts showing this kind of stuff. I have never seen ">="

var results =
     SomeCollection
        .Where(c => c.SomeProperty < 10)
        .Select(c => new {c.SomeProperty, c.OtherProperty});

results.ForEach(x => {Console.WriteLine(x.ToString());})

I'm unsure of how to read this code when it gets to "=>" I clicked on the related article "Lambda Expressions" but it got into what are called "Delegates" which I don't quite understand either.

 

Can you elaborate on your suggestion, or further explain the code from the LINQ page?

 

(Side Note: During the reading of this post I just realized that the Console is an object... "Console.WriteLine" is calling the function write line in the console class/instance. Programming is so illusive, and intuitive.)

Link to comment
Share on other sites

Link to post
Share on other sites

This is what is called an inline function or lambda programming. This means that the Methods "Where" and "Select" can take a generic function of one parameter and returns some value. In the case of Where, a Boolean, and Select, an Object. The notation => is just that, a notation, that can roughly correlate with 

bool private IsProperty(<T> val) {
  return val.field > 1;
}

In-lining is very useful and can make a program much more readable instead of righting one function for every time. In C# these lambda functions (or reference-less functions) are called delegates, they can also be called like this:

var greaterThanTen = someCollection.Where(delegate(int x) {
  return x > 10;
});

 

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, nokel81 said:

This is what is called an inline function or lambda programming. This means that the Methods "Where" and "Select" can take a generic function of one parameter and returns some value. In the case of Where, a Boolean, and Select, an Object. The notation => is just that, a notation, that can roughly correlate with 


bool private IsProperty(<T> val) {
  return val.field > 1;
}

In-lining is very useful and can make a program much more readable instead of righting one function for every time. In C# these lambda functions (or reference-less functions) are called delegates, they can also be called like this:


var greaterThanTen = someCollection.Where(delegate(int x) {
  return x > 10;
});

 

What does 

<T>

do?

I kind of get what's going on in the second expression. It's a shorter way of returning a variable, and a basic function. Does this go inside of functions? Like would you write it in your main, in the class, or outside of the class? (Mostly referring to the Var greater than function, but questioning both.)

This all seems to also make instances of functions?
I found this (Which made me question if it creates instances of functions.)
 

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         
         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

I don't know Lambda math. I only made it through Algebra 2, Trigonometry (I have no calculus knowledge, other than Matrices exist.)

Still reading through, even on the lambda Wikipedia page (Or anonymous function for whatever strange reason) Delegate is still just creating instances of functions.

public class TestDriver
    {
        delegate int SquareDelegate(int d);
        static int Square(int d)
        {
            return d*d;
        }
 
        static void Main(string[] args)
        {
            // C# 1.0: Original delegate syntax needed 
            // initializing with a named method.
            SquareDelegate A = new SquareDelegate(Square);
            System.Console.WriteLine(A(3));
 
            // C# 2.0: A delegate can be initialized with
            // inline code, called an "anonymous method". This
            // method takes an int as an input parameter.
            SquareDelegate B = delegate(int d) { return d*d; };
            System.Console.WriteLine(B(5));
 
            // C# 3.0. A delegate can be initialized with
            // a lambda expression. The lambda takes an int, and returns an int. 
            // The type of x is inferred by the compiler.
            SquareDelegate C = x => x*x;
            System.Console.WriteLine(C(7));
 
            // C# 3.0. A delegate that accepts one input and
            // returns one output can also be implicitly declared with the Func<> type.
            System.Func<int,int> D = x => x*x;
            System.Console.WriteLine(D(9));
        } 
    }


Going to your Inline Functions... it seems they are the same thing as delegate functions (To which I believe you implied.)

Finally I'd like to ask about the => correlation you mentioned. How does it work? What is it called? Is there a link you can provide me with further reading?
All this inline stuff is really new to me, other than it potentially being an instance of functions (by that meaning if it is in anyway similar to instances of objects.)
Thank you for bearing with me and answering all these difficult questions.

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, fpo said:

I'd imagine it to be like 4 spaces vs tabs

Well I think it's a bit more of a fundamental difference in mindset to be honest. The reluctance of some to adopt the use of var due to the notion of the code then being made less readable frustrates me to no ends. In my opinion if the readability of the code is further hampered by the utilisation of a modern language feature then there's something more fundamental going on i.e. violation of good principles and patterns - maybe too much is going on in one place for instance, a bad design and so forth. In other words I view that particular excuse as being as weak as piss...

2 hours ago, fpo said:

if {

}

vs

if

{

}

Ah indent styles; the latter is Allman style, the former is K&R style (or variant). Again this is something that I am somewhat evangelistic about. If there is no clear functional (i.e. JavaScript) or aesthetic necessity to do so then the latter should be used - this again is subjective... more so than the use of var based on my reasons above, again in my opinion...

2 hours ago, fpo said:

I think this forum taught me more about programming than and college professor in a class.

You should have a look at my most recent rant in that case.

2 hours ago, fpo said:

I don't know what you mean by using a non-generic container. My knowledge of how all the functions interact is limited.

2 hours ago, fpo said:

As for the Casting objects where did I do that, and how can I prevent doing that?

Casting was what @nokel81 was demonstrating; in the first example the cast is happening where the explicit type of the variable is declared within the foreach loop declaration and in the second, where it is inferred by var, it's happening where the type is encapsulated within the parenthesis.

 

In relation to what you have just experienced with the ArrayList; it is a non generic container therefore it can contain mostly anything... which is bad. In order to make use of whatever you have put into it, if it's something like a class with public members for instance, you would first have to case it to the correct type and that is slow and difficult to read... which is also bad. What happens if you've put lots of different class instances into it that aren't related or are but at different levels of inheritance - are you going to write a massive maggots nest of if else statements to try type test and cast all of that? Does that feel like the right thing to do in your opinion?

 

Tackling the non generic container issue first; having something that could hold arbitrary things is bad because this is not clear or readable as to what the intention actually is. Moreover it opens up the possibility of abuse and the introduction of bugs, there's no compiler safeguards to stop someone inserting whatever they like into it and then letting things blow up later at some point down the line at run time.

 

The only time it is acceptable to use this kind of container is when you specifically intend to deal with arbitrary things, then you'd make that intention crystal clear by declaring something like a List of type object for instance.

 

To address the issue of casting; put very simply why? Why would you need to convert one thing to another at all - if you needed a specific type then why weren't you using that instead. There are very specific situations where casting is acceptable but this isn't one of them and anytime that it happens it should always be questioned as it almost always point to a bad design. It's not clear, it's not readable and it blurs the intention... avoid it as it is a bad code smell.

2 hours ago, fpo said:

I just learned about Lists (in opposition to ArrayLists) just last night. That appears to be a Generic type.

Yes you are correct, the use of the generic List type would be the optimal choice here.

2 hours ago, fpo said:

Can you elaborate on your suggestion, or further explain the code from the LINQ page?

I think that @nokel81 is doing a great job of covering that in my tardiness. My replies are slow because I'm dyslexic therefore it takes me literally ages to get them typed out and the process can be exhausting at times.

 

The one thing that I would add is caution. As a beginner you should be extremely careful of LINQ in that you should really take the time to consider what exactly is going on underneath that syntactic sugar. It's very easy to be doing unnecessary things and inducing what are known as side effects. Yes crossing paradigms in place into the land of functional programming is exciting and fun but mind your step in this case.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

35 minutes ago, Nuluvius said:

You should have a look at my most recent rant in that case.

Ahh yes. I read through your rant before. I have noticed the abstract concepts being used when explaining programming. None of it made sense to me, nor the others in class. But when I come on the forum, and ask about it, someone shows a specific example of how it works, and then it all makes perfect sense. It was really well thought out and a joy to read. Even though the points were mostly negatively influenced. It is a sorrow on how the education system is mostly based on.
 

 

38 minutes ago, Nuluvius said:

Casting was what @nokel81 was demonstrating; in the first example the cast is happening where the explicit type of the variable is declared within the foreach loop declaration and in the second, where it is inferred by var, it's happening where the type is encapsulated within the parenthesis.

 

In relation to what you have just experienced with the ArrayList; it is a non generic container therefore it can contain mostly anything... which is bad. In order to make use of whatever you have put into it, if it's something like a class with public members for instance, you would first have to case it to the correct type and that is slow and difficult to read... which is also bad. What happens if you've put lots of different class instances into it that aren't related or are but at different levels of inheritance - are you going to write a massive maggots nest of if else statements to try type test and cast all of that? Does that feel like the right thing to do in your opinion?

 

Tackling the non generic container issue first; having something that could hold arbitrary things is bad because this is not clear or readable as to what the intention actually is. Moreover it opens up the possibility of abuse and the introduction of bugs, there's no compiler safeguards to stop someone inserting whatever they like into it and then letting things blow up later at some point down the line at run time.

 

The only time it is acceptable to use this kind of container is when you specifically intend to deal with arbitrary things, then you'd make that intention crystal clear by declaring something like a List of type object for instance.

 

To address the issue of casting; put very simply why? Why would you need to convert one thing to another at all - if you needed a specific type then why weren't you using that instead. There are very specific situations where casting is acceptable but this isn't one of them and anytime that it happens it should always be questioned as it almost always point to a bad design. It's not clear, it's not readable and it blurs the intention... avoid it as it is a bad code smell.

Yes you are correct, the use of the generic List type would be the optimal choice here.

I did look up casting earlier (I believe I linked it in one of my pre-ceding posts.) and it is conversion of variable types (ie. int 1 to float 1.0)
I didn't know I was casting. When I was practicing Java we covered ArrayLists in class. (Teach/learn, not object class) We had to do something with cards (Probably had the same problem I was having last night.) and access functions. The teacher was Chinese and didn't really speak English so I didn't really understand the concepts going on. I just knew you could store multiple objects in an array list. I thought:

"I want to add multiple objects to be commanded at once. I can maybe use an array... Or AN ARRAYLIST CAN STORE OBJECTS! I can use that to remember all the objects selected." I didn't know the potential problems associated with using an ArrayList as opposed to a standard List.
A lot of the problems you discussed make a lot of sense.

 

1 hour ago, Nuluvius said:

I think that @nokel81 is doing a great job of covering that in my tardiness. My replies are slow because I'm dyslexic therefore it takes me literally ages to get them typed out and the process can be exhausting at times.

@nokel81 has been quite the helper. He made a suggestion, and then expanded on your recommendation of enhancements to quite the extent.

 

To note your dyslexia, I actually find it quite helpful. You take your time to come up with very helpful replies. In every post I have seen you make, there was never a word written that wasn't required for the full effect of what you provide. Every word is a useful piece of advice, and explanation. In an online definition it is said that repetition is a commonplace for people that have dyslexia, however your "repetition" is just more ways of explaining, only further helping me understand the concepts. I find your replies to be of some of the highest quality writing I've seen. (Matching against textbooks, online documentation, and highly regarded literature.)

1 hour ago, Nuluvius said:

The one thing that I would add is caution. As a beginner you should be extremely careful of LINQ in that you should really take the time to consider what exactly is going on underneath that syntactic sugar. It's very easy to be doing unnecessary things and inducing what are known as side effects. Yes crossing paradigms in place into the land of functional programming is exciting and fun but mind your step in this case.

It is a very interesting concept. I'm not quite sure if I get it yet. It seems one instance of usage is the creation of instances of functions, however I'm unsure of how you implied the usage in the problem I stated in the beginning. You said I can do away with all loops (specifically for and foreach loops if you didn't mean all) by using LINQ. Can you provide an example, or provide some ideas in how I can implement it with some explanation?

I see the practical use in using LINQ in certain expressions. However I am still lacking the ideas in how to use it in my problem.

Link to comment
Share on other sites

Link to post
Share on other sites

18 hours ago, fpo said:

What does 


<T>

do?

The T is a generic type parameter, have a read of this.

18 hours ago, fpo said:

I don't know Lambda math. I only made it through Algebra 2, Trigonometry (I have no calculus knowledge, other than Matrices exist.)

This is not the same thing.

18 hours ago, fpo said:

Still reading through, even on the lambda Wikipedia page (Or anonymous function for whatever strange reason) Delegate is still just creating instances of functions.

I think that this offers a relatively decent explanation of the difference between the two. Also have a read of Lambda Expressions and Delegates.

18 hours ago, fpo said:

Going to your Inline Functions... it seems they are the same thing as delegate functions (To which I believe you implied.)

The link that you have provided pertains to a different concept that is applicable to C++. In that context the use of the inline keyword will cause the compiler to explicitly insert the code in the places where it is called. This is quite powerful as it will save a call to the method since the code will physically be there each time. This can however have the side effect of increasing the size of the compiled code as code is then duplicated in many places.

 

In C# it's a bit different, if we have a lambda or a delegate and we pass this to somewhere else as a parameter or indeed even call it later on after declaration in the same place we are still using a reference to an object i.e. there's still only one place where it exists and unlike inlining there's going to be an associated call involved.

18 hours ago, fpo said:

Finally I'd like to ask about the => correlation you mentioned. How does it work? What is it called? Is there a link you can provide me with further reading?

That is the Lambda Operator.

16 hours ago, fpo said:

It is a very interesting concept. I'm not quite sure if I get it yet. It seems one instance of usage is the creation of instances of functions

When you look at those expressions that you pasted, the anonymous function is actually instantiated in place as a parameter that is then consumed by the method.

16 hours ago, fpo said:

however I'm unsure of how you implied the usage in the problem I stated in the beginning. You said I can do away with all loops (specifically for and foreach loops if you didn't mean all) by using LINQ. Can you provide an example, or provide some ideas in how I can implement it with some explanation?

I see the practical use in using LINQ in certain expressions. However I am still lacking the ideas in how to use it in my problem.

I was more meaning that it may be more readable to do away with very simple loops by instead using the List.ForEach method. I wouldn't exchange a loop that was non trivial for this however. I also wanted to stress that you should be very careful when using LINQ and lambda expressions in general because it's very easy to induce side effect and blunder into performance problems.

 

This article does a great job of explaining some of the common concerns that one must be mindful of. Of particular interest is the last example where he discusses side effects; essentially when you declare lambda expressions such as is the case in the Where clause they don't actually get executed until the expression chain is evaluated. This means that if you have captured something like a file resource and it happens to 'go away' (get disposed) before you evaluate your expression by calling ToList for example then it has the potential to blow up as it will be operating on something that no loner exists. The performance pitfalls are a bit easier to see, be careful about double filtering, translating and iterating. Other best practices are touched on as well and there's much more to be found on the web besides.

 

If you like LINQ then you should have a look at PLINQ as well.

16 hours ago, fpo said:

I find your replies to be of some of the highest quality writing I've seen. (Matching against textbooks, online documentation, and highly regarded literature.)

Thank you :$

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

On ‎12‎/‎31‎/‎2016 at 10:53 AM, Nuluvius said:

The T is a generic type parameter, have a read of this.

Okay it makes a bit more sense with that documentation.

On ‎12‎/‎31‎/‎2016 at 10:53 AM, Nuluvius said:

This is not the same thing.

Sorry I played Black Mesa recently and you have to go to the Lambda Facility at some point, so I just assumed it was some kind of physics/calculus thingy.

On ‎12‎/‎31‎/‎2016 at 10:53 AM, Nuluvius said:

I think that this offers a relatively decent explanation of the difference between the two. Also have a read of Lambda Expressions and Delegates.

On ‎12‎/‎31‎/‎2016 at 10:53 AM, Nuluvius said:

In C# it's a bit different, if we have a lambda or a delegate and we pass this to somewhere else as a parameter or indeed even call it later on after declaration in the same place we are still using a reference to an object i.e. there's still only one place where it exists and unlike inlining there's going to be an associated call involved.

That is the Lambda Operator.

It makes a lot more sense. I understand how to use both of them now. It's a pretty cool idea.

On ‎12‎/‎31‎/‎2016 at 10:53 AM, Nuluvius said:

This article does a great job of explaining some of the common concerns that one must be mindful of. Of particular interest is the last example where he discusses side effects; essentially when you declare lambda expressions such as is the case in the Where clause they don't actually get executed until the expression chain is evaluated. This means that if you have captured something like a file resource and it happens to 'go away' (get disposed) before you evaluate your expression by calling ToList for example then it has the potential to blow up as it will be operating on something that no loner exists. The performance pitfalls are a bit easier to see, be careful about double filtering, translating and iterating. Other best practices are touched on as well and there's much more to be found on the web besides.

I'll be sure to watch out for those pitfalls. Thanks for the warnings!

Link to comment
Share on other sites

Link to post
Share on other sites

I don't know wether this has been resolved or not, as I couldn't be bothered to read through all that text (it sort of went off-topic). I don't know what you're trying to accomplish either, but I do potentially see the error.

 

First of all, as mentioned earlier just use a "List<>" and remember to specify the type. Second of all, the "ExecuteCommand" method in the "ControlledObject" class is private because you haven't specified a scope. This means that you can't access the method from a different class.

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, Helius said:

I don't know wether this has been resolved or not, as I couldn't be bothered to read through all that text (it sort of went off-topic). I don't know what you're trying to accomplish either, but I do potentially see the error.

 

First of all, as mentioned earlier just use a "List<>" and remember to specify the type. Second of all, the "ExecuteCommand" method in the "ControlledObject" class is private because you haven't specified a scope. This means that you can't access the method from a different class.

Thank you.
The problem was resolved however. Your input is still valid, and appreciated.
We did cover using Lists in favor of Array Lists.

I did forget to include the part of the code in which the second class is allowed to be used in the first class. In my actual code I did appropriately call the code. Everything in my program works as I intended.

I forgot to set best answer as I wasn't sure if a best answer was going to be made after my problem was resolved as I discussed a lot with Nuluvis (I think that's how it is spelled.)

We went a bit off topic for discussions in other ways to access functions. I tried to document and link everything I could for other potential readers. I find everything very interesting, so if you get a chance and want to learn about Lambda functions, there's a lot there.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×