Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a list in one class. And I need to populate the list from another class. Then I need to access the list one or two other classes. I don't want to use static list. How is this done in C#. I tried my best. But not successful. Can anybody show example?.
use get I would suggest
This is where the list is
class A
{
private list<Objects> myList = new list<Objects>();
public list<Objects> getList()
{
return myList;
}
}
This is where you want to use it
class B
{
private list<Objects> myNewList = new list<Objects>();
A a = new A();
public void setList()
{
myNewList = a.getlist();
}
}
Something like this. Remember same namespace for classes to know each other, if in different files
This sounds like a job for a public property.
// I'm assuming a List of strings, fix accordingly
public class A
{
//Not autoimplemented to ensure it's always initialized
private List<string> items = new List<string>();
public List<string> Items
{
get { return items; }
set { items = value; }
}
}
public class AnyoneElse
{
void someMethod()
{
A someVar = new A();
someVar.Items.Add("This was added from outside");
MessageBox.Show(someVar.Items.First());
}
}
Access modifiers should be tweaked appropriately (they depend on your namespace structure, mostly. Also, are the class and the consumers in the same assembly or not ? Anyway, the point should be clear enough).
This is a basic example of what you need
public class YourOriginalClass
{
/// <summary>
/// The list you want to access
/// </summary>
public List<YourType> YourList {
get;
set;
}
}
// Here another class where you can use the list
public class YourSecondClass
{
public void EditMyList()
{
YourOriginalClass test = new YourOriginalClass();
test.YourList = new List<YourType>();
// then you can populate it
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make functions to "send" NPCs to specific rooms by adding them to the room's humansHere list, and one to get this list (and print it later, but I don't need help with that). But I get this error message:
Argument 1: cannot convert from 'System.Collections.Generic.List<Game02.Human>' to 'Game02.Human'
Once I get that fixed, I'm sure I'll figure out the rest, so feel free to ignore this: I need to know how to call this function for specific rooms. Something like:
LivingRoom.GetHumansHere() or Kitchen.SetHumansHere(_lyndonJohnson). Or will this work as it is?
public class Room
{
public int ID { get; set; }
[...]
private List<Human> humansHere;
public List<Human> GetHumansHere()
{
return humansHere;
}
public void SetHumansHere(List<Human> x)
{
humansHere.Add(x);
}
}
public class Human : LivingCreature
{
public int Gold { get; set; }
public List<InventoryItem> Inventory { get; set; }
public Human(string name, int currentHitPoints, int maximumHitPoints, int gold) : base(name, currentHitPoints, maximumHitPoints)
{
Gold = gold;
}
}
Thank you to Dmitry for making it work, and thank you to Jonathan for explaining the problem:
The problem is you are trying to add a LIST of humans to a list rather than a single human to a list
Two possibilities:
If you want to add one person only, change method's signature:
public void SetHumansHere(Human person)
{
if (null == person)
throw new ArgumentNullException(nameof(person));
humansHere.Add(person);
}
If you want to add a collection of persons in one go, use AddRange
// IEnumerable<Human> - let's generalize the method
// and allow to add not only List, but other collections, say, array
public void SetHumansHere(IEnumerable<Human> persons)
{
if (null == persons)
throw new ArgumentNullException(nameof(persons));
humansHere.AddRange(persons);
}
you need to use List.AddRange, Adds the elements of the specified collection to the end of the List.
public void SetHumansHere(List<Human> x)
{
humansHere.AddRange(x);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying this simple code below but surprisingly the compiler says
"the name pq does not exist in current context"
However as you see it´s inside the desired scope. Even with adding getters and setters I can´t do that.
namespace AskYourQuestion
{
public struct QuestionNum
{
public string Q1;
}
class Questions
{
QuestionNum pq = new QuestionNum();
pq.Q1 = "hi";
}
}
I want to make a struct with some strings and create some classes that initialize the strings in specific languages and in main program depends on the user language, the strings appear for him.
Here are few inputs to help you further dissect the problem.
Current:
namespace AskYourQuestion
{
public struct QuestionNum
{
public string Q1;
}
class Questions
{
QuestionNum pq = new QuestionNum();
// pq.Q1 = "hi"; --> This will not work
// Why? See below
}
}
Class is a specification where we encapsulate the members it should hold.
Here the Questions class encapsulate a member pq of type QuestionNum and we should specify on how the Questions class and it's encapsulating members would be constructed.
Different ways to do this:
Default it: QuestionNum pq = new QuestionNum() { Q1 = "Hi" };
Construct it: public Questions(string defaultValue) { this.pq.Q1 =
defaultValue; }
Methods / setters
Examples for each:
Default it:
namespace AskYourQuestion
{
public struct QuestionNum
{
public string Q1;
}
class Questions
{
internal QuestionNum pq = new QuestionNum() { Q1 = "Hi" };
}
}
Construct it:
namespace AskYourQuestion
{
public struct QuestionNum
{
public string Q1;
}
class Questions
{
internal QuestionNum pq = new QuestionNum() { Q1 = "Hi" };
public Questions()
{
}
public Questions(string defaultValue)
{
this.pq.Q1 = defaultValue;
}
}
}
To use it:
Questions quest = new Questions("World");
Console.WriteLine(quest.pq.Q1);
There are many other ways, but you need to choose the best case based on your problem.
You should put that line in a method or constructor...
public class Questions
{
QuestionNum pq = new QuestionNum();
Questions()
{
pq.Q1 = "hi";
}
}
You can also
public struct QuestionNum
{
public string Q1;
}
public partial class Form1 : Form
{
QuestionNum pq = new QuestionNum()
{
Q1 = "something"
};
}
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 5 years ago.
Improve this question
Is there a way to write this so I don't have to explicitly declare the field _D?
How do I get around the = new List<T>() when the class is implemented?
What I have:
class c {
private List<T> _D = new List<T>();
public List<T> D { get { return _D; } set { _D = value; } }
}
What I want:
class c {
public List<T> D { get; set; }
}
Wouldn't it be better to declare a constructor to assign the property a List<T>? As in:
class c {
c() { D = new List<t>(); }
public List<t> D { get; set; }
}
What are today's best practices when implementing properties and assigning initial values?
All three are technically correct. I found the first in a bit of code I'm taking over. I can't find any purpose behind the original code that declares all the property backing fields. I thought declaring backing fields was not a best practice since c# v3 .. except when you are actually going to use the private field somewhere in the class's methods, which isn't happening here.
You could look at assigning the initial List<> to the property as 'Using the property somewhere in the class.'
Or you could look at it as 'Pointless, do it like my third example instead.'
Which is generally regarded as best practice these days?
Since C# 6 you can do it this way:
public IList<int> Prop1 { get; set; } = new List<int> { 1, 2, 3 };
There are a few ways to achieve the same thing in .NET as well as best practices and recommendations. It all depends on your requirements and responsibilities for the object and properties. I saw a comment with a link to the programming guide which is excellent. These are just a few more examples.
public class C<T>
{
public List<T> D { get; set; } = new List<T>();
}
public class C2
{
public IReadOnlyList<int> D { get; private set; }
public C2()
{
D = new List<int>();
}
}
public class C3
{
private List<int> _d = null;
public List<int> D
{
get
{
return _d ?? new List<int>();
}
}
}
I'm working on a testing platform app for students. Since the question can have one or multiple correct answers, I need radio buttons/checkboxes for selecting the right one(s). I would like to implement an abstract class with an Add method. From it, derive two classes, each of them containing an array of RaddioButtons or Checkboxes. Is there a better way to do this than the one listed below? I mean, can the add method be put in the abstract class?
public class AnswerForm
{
public static int no;
public AnswerForm()
{
no=0;
}
}
public class RadioButtonClass:AnswerForm
{
RadioButton[] vector;
public void Add(RadioButton rbutton)
{
vector[no++] = rbutton;
}
}
public class CheckBoxClass : AnswerForm
{
CheckBox[] vector;
public void Add(CheckBox cbox)
{
vector[no++] = cbox;
}
}
I also have two vectors in which I put a fixed number of elements, RadioButtons and Checkboxes. These elements exist in the Windows Form Form1.cs[design]. What I would like to do is pass one an element of type AnswerForm to a function and in the function, based on what type of question I have, allocate memory to my AnswerForm object for one of the derived classes. Also, it might be easier if the Add method would have as parameter a s string, and vector[no++].Text=s;
The prototype of the function:
public void readQuestions(RichTextBox richTextBox, AnswerForm answerForm)
Here I'm parsing an XML file and put the objects in a List. The XML contains Questions, each having a type(multiple or single answer), the text which goes to the richTextBox, and the answers. Next i'm looping through the question list and check question's type. If multiple answers, then put each answer in a CheckBox.Text. Else, put it in a RadioButton.Text. Before assigning the text to each WinForm element, I would like to allocate the corresponding object type(RadioButtonClass or CheckBoxClass) and then use the add method for each answer of the current question. That is why I thought of inheritance, abstractization an polymorphism.
This is how it look like now:
public void readQuestions(RichTextBox richTextBox, AnswerForm answerForm)
{
var file = XDocument.Load("QuestionsTest.xml");
var subject = new Subject();
subject.Name = (string)file.Root.Attribute("Subject");
var questions = from question in file.Root.Elements("Question")
select new Question
{
NumberOfCorrectAnswers=(int)question.Attribute("NumberOfAnswers"),
Text = (string)question.Element("Text"),
Answers = new List<Answer>(
from answers in question.Element("Answers").Elements("Answer")
select new Answer
{
Text = (string)answers
})
};
using (var db = new TestingPlatformContext())
{
db.Subjects.Add(subject);
foreach (var question in questions)
{
//Console.WriteLine("Subject: {0}\n Text: {1}", question.Subject, question.Text);
richTextBox.Text = question.Text;
//db.Questions.Add(question);
foreach (var answer in question.Answers)
//Console.WriteLine("Answer: {0}", answer.Text);
if (question.NumberOfCorrectAnswers != 1)
{
answerForm = new CheckBoxClass();
answerForm.Add(answer.Text);
//db.Answers.Add(answer);
}
else
{
answerForm = new RadioButtonClass();
answerForm.Add(answer.Text);
}
}
}
}
Yes, you can move the Add() method to parent class, using generic:
public class AnswerForm<T>
{
private readonly IList<T> _list;
public AnswerForm()
{
_list = new List<T>();
}
public void Add(T button)
{
_list.Add(button);
}
}
public class RadioButtonClass:AnswerForm<RadioButton>
{
}
public class CheckBoxClass : AnswerForm<CheckBox>
{
}
I made a few changes:
- Use list instead of array, it's more flexible in this case
- Use generic in parent class AnswerForm
A solution, much simple, would be like this:
public class AnswerForm
{
public static int no;
private RadioButton[] rbuttons;
private Checkbox[] checkboxes;
public AnswerForm()
{
no=0;
rbuttons = new RadioButton[]
{
radioButton1,radioButton2,radioButton3,radioButton4,radioButton5
};
checkboxes = new CheckBox[]
{
checkBox1,checkBox2,checkBox3,checkBox4,checkBox5,checkBox6
};
}
public void AddRadio(string s)
{
rbuttons[no++].Text=s;
}
public void AddBox(string s)
{
checkboxes[no++].Text=s;
}
}
But this is far from elegant.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The below code:
public struct Value
{
List<string> RFcode;
int found;
int expected;
public int Found { get { return found; } }
public int Expected { get { return expected; } }
public List<string> Code { get { return RFcode; } }
public Value(int f, int exp, string s)
{
this.found = f;
this.expected = exp;
RFcode.Add(s);
}
}
is Invalid. On VS debug I get :
Error 1 Field 'BE_EOR.InvCyclic.Value.RFcode' must be fully assigned before control is returned to the caller
Error 2 Use of possibly unassigned field 'RFcode'
Please try this one:
List<string> RFcode = new List<string>();
The reason, why you get this error is the fact, that you haven't created a list, which will hold the strings you want. However, you try to add elements in this list:
RFcode.Add(s);
This line of code, List<string> RFcode;, it justs defines a variable called RFcode, that will keep a reference to a List of strings. Neither it creates a list nor it assings it to this variable.
Update
As already Christian Sauer has pointed out and Kensei have reminded it to us, it would be better you use a class rather than the struct you use:
public class Value
{
public List<string> RFCode { get; set; }
public int Found { get; set; }
public int Expected { get; set; }
public Value(string s, int found, int expected)
{
RFCode = new List<string> { s };
Found = found;
Expected = expected;
}
}
However, at this point I have to raise a question. Why are you using a List of strings, since you only pass a string to your constructor? If that's the case, to pass only a string, I don't think that's a good design, since you don't use the most appropriate type for that you want.