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
I have a class in which I operate some methods.
public class MyClass
{
public static List<ObjectA> MyField;
public static Object MyMethod()
{
List<ObjectA> anotherObjectA = new List<ObjectA>();
// I do something with anotherObjectA...
// after processing something now I want to keep the current status of anotherObjectA to MyField:
MyField = anotherObjectA;
// and now I want to work just with anotherObjectA. The problem is that whatever I work with anotherObjectA it changes also MyField
}
}
How can i achieve what I am trying to do
You can do
MyField = new List<ObjectA>(anotherObjectA);
This will create a copy of the list. However, any changes to the objects in the list will be visible in both. You'll have to decide for yourself how deep your copy has to be. If you really want a deep copy, you'll need to provide a mechanism for ObjectA to make a copy of itself, iterate over the original list, and add a copy of each object to the target list.
MyField and anotherObjectA reference same object. So if you change MyField it also changes anotherObjectA.
So First you need to create two List objects:
MyField = new List<ObjectA>(anotherObjectA);
This will create two list objects but the ObjectA objects inside the list are still referencing to the same.
MyField.First() == anotherObjectA.First() // returns true;
If you want to make a complete copy you also need to create a copy of objects inside anotherObjectA
public class ObjectA
{
public ObjectA() { } // Normal constructor
public ObjectA(ObjectA objToCopy) { /* copy fields into new object */ }
}
MyField = anotherObjectA.Select(obja => new ObjectA(obja)).ToList();
with this solution, changing objects inside MyField will not affect objects inside anotherObjectA unless ObjectA also contains reference types.
Related
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 2 years ago.
Improve this question
I have this nested list :
public List<List<string>> pcList = new List<List<string>>();
How can I create getters and setters for it?
I have tried everything out there on the internet and nothing seems to work
Thx!
EDIT:
So, In class Pc I have this code:
class PC
{
public List<List<string>> pcList = new List<List<string>>();
public List<string> subList = new List<string>();
}
so the pcList is the "parent" list and the sublist is actually the place where I add each pc with its info.
I have a method where I populate the lists. Then I want to use an object of this class in another class called X, let's say.
I have tried to simply access the lists by using object.ListName but it doesn't work.
You can use auto property - just add {get;set;} (note that usually properties are upper case)
public List<List<string>> PcList {get;set;}
public List<List<string>> pcList { get; set; } = new List<List<string>>();
This is a variable.
If you want a property declare it like:
public List<List<string>> pcList {get;set;}
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 3 years ago.
Improve this question
Consider a simple class
public class MyClass
{
private int myProperty
...
public int MyProperty
{
get
{
return myProperty;
}
set
{
// some evaluation/condition
myProperty= value;
}
}
...
}
Now, if I want to create an empty constructor where I set default values for the class properties I could do this either this way:
public MyClass()
{
myProperty = 1;
...
}
or this way:
public MyClass()
{
MyProperty = 1;
...
}
Both examples seem valid, since I would never set a default value, that doesn't meet the requirements in the setter evaluation.
The question is, is there a best practice or doesn't it matter anyway?
What would be the advantage of one or the other be (as I can't find any)? Is there some reference, where this question is adressed?
So far I have come across code from many different developers that use either or both ways...
You can use both. But i prefer the first one. Why? Because the value that the property uses is directly assigned. For C# 6 above, you can use default value in a property directly without using constructor.
public class Person
{
public string FirstName { get; set; } = "<first_name>";
public string LastName { get; set; } = "<last_name">;
}
I personally like to set it as you done in first block.
For me it serve as additional fact of method is constructing object, not using alredy constructed. Also it makes me sure that properties is not called (they transform to set/get functions which results in couple of excess instruction).
But i believe that both variants are valid and maybe compiler optimizes properties to direct assignment.
For simple data first method is ok. But on more complex data, you could have a condition in the set (depending to another variable for example, set { if (Config.TestEnv) ...} so if you directly set the private value, you could be in trouble.
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
public class Kuku
{
private LinkedList<MyClass> m_list;
public IEnumerable<MyClass> Locations { get { return m_list; } }
}
I need to implement in public class FindAllMyClass
the method which iterates all MyClass objects in Kuku - I don't know how do I use Locations property from Kuku.
Should I define IEnumerable Locations or just make LinkedList m_list to be public property?
Should I define IEnumerable<MyClass> Locations or just make LinkedList<MyClass> m_list to be a public property?
public class FindAllMyClass
{
public void itMethod(Kuku input)
{
//This is not correct
foreach (MyClass c in input.Locations)
{
}
}
}
Why to define IEnumerable Locations and not just make LinkedList m_list to be public property?
Several possible reasons:
What if later you decide you don't want to implement it as a LinkedList<> but as a regular List? Or a lazy-loaded collection type? or an array?
Exposing the collection as a generic IEnumerable<T> allows you to change out the internal implementation later without changing the public contract.
If you make the collection a property (with get; set; accessors) you are allowing clients to add to, remove from, even replace the entire list. Exposing it as IEnumerable indicates that the list is intended to be read-only (unless you expose Add methods somewhere else).
I don't know how do I use Locations property from Kuku.
Sure you do - you're already doing it in your sample:
foreach (MyClass c in input.Locations)
{
}
Or you can use Linq to search for or aggregate data from the collection (foreach is still appropriate for updating the instances.
You could use LINQ to object:
input.Locations.Where(x=> x.Property1 == value1 && x.Property2 > value2);
IEnumerable gives you a way to expose a list from your class which has the following properties:
It is implementation independent - you can change what sort of list you use internally without needing to change everything which uses your class
It integrates well with LINQ, foreach and various other language constructs
It provides a read only view on the list, so no chance of others updating the list (inserting/deleting items)
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
For example:
class WebCrawler
{
List<string> currentCrawlingSite;
List<string> sitesToCrawl;
RetrieveWebContent retwebcontent;
public WebCrawler()
{
}
}
When I make WebCrawler = new WebCrawler(parameter here)...
Add another constructor to your class;
public WebCrawler(parameter here)
{
}
After that, you need to remove parameterless one constructor, so people can create an instance of your class without provide any parameters.
You can create an instance of it like
WebCrawler w = new WebCrawler(parameter here);
You can read for more informations from Instance Constructors
Here is a DEMO.
Create constructor with parameter you want to be provided by user:
public WebCrawler(string param1, int param2)
{
}
When any constructor like that is added the default one (parameterless) is no longer available, unless you write it yourself:
public WebCrawler()
{
}
So just remove it, and user won't be able to create your class instance object without providing these parameters. You can also make the same setting parameterless constructor private or protected.
Instance Constructors (C# Programming Guide)
You can make the parameter-less constructor private...
private WebCrawler()
{
}
Meaning no consumers/callers have the ability to call it.
You then have only one constructor that they can use:
public WebCrawler(string something)
{
}
Add another constructor accepting a parameter:
public WebCrawler(string someParameter)
{
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a test class that I created and I want to be able to create multiple instances of it. Then I want to use foreach to iterate thru each instance. I have seen several forums that show IEnumerate but being a very newbe they have me confused. Can anyone please give me a newbe example.
My class:
using System;
using System.Collections;
using System.Linq;
using System.Text
namespace Test3
{
class Class1
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
}
Thanks
Do you need to enumerate through multiple instances of your type, or create a type that is itself enumerable?
The former is easy: add instances to a collection, such as List<T>() which implement IEnumerable<T>.
// instantiate a few instances of Class1
var c1 = new Class1 { Name = "Foo", Address = "Bar" };
var c2 = new Class1 { Name = "Baz", Address = "Boz" };
// instantiate a collection
var list = new System.Collections.Generic.List<Class1>();
// add the instances
list.Add( c1 );
list.Add( c2 );
// use foreach to access each item in the collection
foreach( var item in list ){
System.Diagnostics.Debug.WriteLine( item.Name );
}
When you use a foreach statement, the compiler helps out and automatically generates the code needed to interface with the IEnumerable (such as a list). In other words, you don't need to explicitly write any additional code to iterate through the items.
The latter is a bit more complex, and requires implementing IEnumerable<T> yourself. Based on the sample data and the question, I don't think this is what you are seeking.
How do I implement IEnumerable?
IEnumerable vs List - What to Use? How do they work?
Your class is just a "chunk of data" - you need to store multiple instances of your class into some kind of collection class, and use foreach on the collection.
// Create multiple instances in an array
Class1[] instances = new Class1[100];
for(int i=0;i<instances.Length;i++) instances[i] = new Class1();
// Use foreach to iterate through each instance
foreach(Class1 instance in instances) {
DoSomething( instance );
}