C#: I cant access my struct members [closed] - c#

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"
};
}

Related

Anonymous type with var gives error CS0825 [duplicate]

This question already has answers here:
Implicit typing; why just local variables?
(6 answers)
Closed 1 year ago.
I want to create an anonymous type in C# inside a class.
The examples I have seen use var to create an anonymous variable
var RecordId = new
{
Foo = 0,
Bar = "can be also a string"
};
However I want to create my anonymous variable inside a class.
public class Logger //: LogBase
{
var RecordId = new
{
Foo = 0,
Bar = 1
};
}
So when Logging I can do:
Logger.RecordId.Foo
But declaring my anonymous type as var triggers the following error:
CS0825: The contextual keyword 'var' may only appear within a local variable declaration.
What is the type of an anonymous variable, so I don't have to use var?
I understand what the error is telling me, but I don't want to move my variable inside a function, it needs to be a property of Logger.
Edit: enum is what I tried t the beginning, but I need the values to be more flexible than just integers (like strings, so I can dump jon files).
I updated my question to reflect that.
var (and by definition anonymous types) can only be declared inside a method, the error message is basically telling you that. If you need this type to be at class level, then make a class/struct/tuple to store it.
public static class Record
{
public static int Foo { get; set; }
public static int Bar { get; set; }
}
public class Logger //: LogBase
{
public static Record RecordId { get; set; } = new Record();
}
Now you can do this:
var foo = Logger.RecordId.Foo;
Note that I also used static so you don't need to create a new instance of the class, but change that if you think it's relevant.
public class Logger //: LogBase
{
public enum RecordId
{
Foo = 0,
Bar = 1
}
}
If you do not want strings you can do the above.
public class LogCategory
{
private LogCategory(string value) { Value = value; }
public string Value { get; private set; }
public static LogCategory Foo { get { return new LogCategory("Foo"); } }
public static LogCategory Bar { get { return new LogCategory("Bar"); } }
}
If you want strings you could create your own class something like the above.
You can use the dynamic type to have an anonymous instance variable.
public class Foo
{
dynamic bar = new {
A = 1,
B = 2
};
public void Print() {
Console.WriteLine(bar.A);
}
}
Try it out!
Just because you can do this doesn't mean it's a good idea. See DavidG's answer for an alternative using a strongly-typed object that will not require you to expose your code to the many problems associated with the dynamic type.

c# class declaration of properties [closed]

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>();
}
}
}

C# referencing a methods variables from another method [closed]

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 6 years ago.
Improve this question
Sometimes it happens that I want to use a lot of Method As variables in Method B.
Usually its quite a pain to pass all the variables to this method, especially if I have to do this a lot of times (but cannot simply copy paste, because some things change) or am just to lazy.
Is there such a thing like a "inner Method"? Or some concept to handle this in an easy way?
What I want to do:
public void A()
{
int a = 4;
string b = "Hello World";
B(ref vals);
//Or like so
C(ref current);
}
public void B(ref AllValues)
{
a = 3;
...
}
public void C(ref MethodThatSharesAllValues method)
{
method.a = 3;
...
}
If they all are in the same class
You can configure them as class variables:
public class MyClass{
//set this as private/protected/public or nothing and you can also set a default value
int a;
public void A()
{
a = 4;
string b = "Hello World";
B();
C();
}
public void B()
{
a = 3;
...
}
public void C()
{
a = 3;
...
}
}
Elseway
public static class MyClassA{
public static int a = 0;
public static void MethodA(){
this.a = 3;
}
}
now from method B you can access MyClassA
int myExValueA = MyClassA.a;
Elseway you gotta pass them as parameters
hope this helps
You can create a class which will hold your parameters and then pass only an instance of this class
public void metA(Parameters input)
{
input.a = 5;
input.c = "hello";
metB(input);
}
public void metB(Parameters input)
{
input.b = 10;
}
public class Parameters
{
public int a;
public int b;
public string c;
}
You can declare the variables static in a class header and use them as you like, private if are in the same class, protected for child classes, internal or public else. Or box the variables in a class like this:
public class Foo
{
public int A { get; set; }
public int B { get; set; }
public string C { get; set; }
}
If passed variables are the same type you can use data structure like int[] or string[] or List<int> or List<string> and pass them without ref but this has the disadvantage that more than often you would not use all varibales from the structure as it is also the case with the class boxing variant.
Something like the following:
public void foo() {
int a = 10;
// ...
}
public void foo_bar() {
// "a" is not in scope for foo_bar, so this won't compile
a = 20;
// ...
}
would definitely be invalid. I don't think that this was what you were driving at in your question though.
You can do something somewhat similar to what you ask for using closures but they're a bit tricky to work with. Basically, something like this would be valid (and I'm not sitting in front of an IDE so forgive me if the syntax is a little off):
Func<int> GetCounter() {
int count = 0;
// This will capture the count variable from its context
Func<int> method = () => ++count;
return method;
}
While a fair number of languages (including some versions of C++ now I guess) have closures (or some similar variant), there seems to be little consistency in exactly how they work across languages (e.g. on whether the "count" variable should be immutable once it's captured) so it's important to check the documentation for the language you're using (in this case, C#) to understand exactly how they work.
In terms of the first code sample I provide, I doubt that that's what you were asking about, but just as a brief digression you probably wouldn't really want it to be the allowable anyway (and again I suspect that this isn't the syntax/semantics you're asking about) as it would quickly lead to unexpected/undefined behavior. For example:
If you have a local variable a that's initialized in Foo() and you refer to it in Foo_Bar() before you run Foo(), what should its value be?
If you run Foo() to initialize the variable, edit the variable in Foo_Bar(), and then run Foo() again, should you re-initialize the variable or allow it to remain what Foo_Bar() set it to?
Is it safe to garbage collect a local variable after the method call completes, or might it be referred to again?
See the following:
public class SomeObject
{
public int SomeProperty { get; set; } = 6;
// ...
}
public class SomeOtherObject
{
// ..
}
void foo() {
// What is the content of "a" before foo() runs?
object a = new SomeObject();
// Which "a" should this refer to - the one in foo() or the one in foo_bar()?
// Also, is this a valid cast given that we haven't specified that SomeOtherObject can be cast to SomeObject?
var b = (SomeObject)a;
// If we run foo() again, should "b" retain the value of SetProperty or set it back to the initial value (6)?
b.SetProperty = 10;
// ...
// Is it safe to garbage collect "a" at this point (or will foo_bar refer to it)?
}
void foo_bar() {
object a = new SomeOtherObject();
// ...
}

Inheritance. Polymorphism. Abstractization

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.

Add to a List from two Classes in C# [closed]

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
}
}

Categories

Resources