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>();
}
}
}
Related
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 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 7 years ago.
Improve this question
Does a property need to be explicitly initialized like so:
public DeviceSettings ds{ get; private set; } = new DeviceSettings();
Or is it OK to keep it this way?
public class MyDevice
{
public MyDevice(string serial, int patientid)
{
}
public DeviceSettings ds{ get; private set; } //no initialization needed?
}
In your first example ds is set to a new instance of DeviceSettings, in your 2nd example ds is set to default(DeviceSettings) which if that type is a class will be null.
If you wish to do it the 2nd way and your type is a class you will need to add the assignment in the constructor
public class MyDevice
{
public MyDevice(string serial, int patientid)
{
ds = new DeviceSettings();
}
public DeviceSettings ds{ get; private set; }
}
Properties don't need to be initialized at the time you create a new instance of your class. That depends mostly of your business logic.
Property Initializers can help you when you want to initialize your property with a default value,eg:
private DateTime CreateOn { get; } = DateTime.UtcNow;
Which is translated to something like this:
private readonly createOn= DateTime.UtcNow;
public DateTime CreateOn
{
get
{
return createOn;
}
}
That is a property that is going to remain immutable after its initialization.
As #ScottChamberlain pointed out in his answer, you can initialize an auto-implemented property in the constructor of your class. That is a good place to initialize your property if this depends of an external value that is passed as parameter to the constructor, eg:
public class Product
{
private PriceCalculator Calculator {get;set;}
public decimal Price{get {return Calculator.GetPrice();}}
public Product(int factor)
{
Calculator=new PriceCalculator(factor);
}
}
public DeviceSettings ds{ get; private set; } = new DeviceSettings();
That syntax was introduced only in C# 6.0. So it's completely fine do not initialize it. In that case, it will get default value (depends on DeviceSettings, is it value or reference type)
No initialization are needed for instantiate your class.
If you're going to use property, you need to initialize it to have a correct value (it will mainly be null, because null is default value in many cases, except if your redefine it or use a struct). You can do it with C#6 syntaxic sugar as your first example, or in constructor.
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.
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 );
}
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
}
}