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.
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 already checked the link "Why can't I set “this” to a value in C#?" and I know that this is read-only. In other words, it (the content) cannot be assigned to another new object. I am just wondering that the philosophy or the consideration of this constraint in C#. If the reason is about to the safety of memory management, C# employs garbage collector and the usage in the future to an object would be determined.
public class TestClass
{
private int Number;
public TestClass()
{
this.Number = 0;
}
public TestClass(TestClass NewTestClass)
{
this = NewTestClass; // CS1604 Cannot assign to 'this' because it is read-only
}
}
As the result, it seems that the members needs to be updated one by one.
public TestClass(TestClass NewTestClass)
{
this.Number = NewTestClass.Number; // Update members one by one.
}
Any comments are welcome.
Note: For clarifying, the C++ part has been removed.
I don't think you are quite familiar with what dereferencing a pointer is.
Let's look at this method:
void TestClass::SetThisTest() {
*this = TestClass(this->IncreaseNumber().GetNumber()); // Assign new object to *this
}
You believe you are replacing the this, but you aren't. You are replacing the contents pointed to by this. Huge difference. *this != this.
Try this:
void TestClass::SetThisTest() {
std::cout << "this' address is " << std::to_address(this) << std::endl;
*this = TestClass(this->IncreaseNumber().GetNumber()); // shallow copy!
std::cout << "Now this' address is " << std::to_address(this) << std::endl;
}
The address doesn't change, but, the values this points do does. You are invoking (in this case) default shallow copy.
You can do this in C# very easily, you just aren't allowed to be that direct about it.
Here is the C# equivalent of your C++ class:
public sealed class ThisTest
{
private int _myNumber;
public ThisTest() { }
public ThisTest(int number) { _myNumber = number; }
public static void ShallowCopy(ThisTest to, ThisTest from)
{
to._myNumber = from._myNumber;
}
public int GetNumber() => _myNumber;
public ThisTest IncreaseNumber()
{
_myNumber += 1;
return this;
}
public void SetThisTest()
{
ShallowCopy(this, new ThisTest(this.IncreaseNumber().GetNumber()));
}
}
Because "this" is a reference to the object you instantiated that is only accessible from the object itself.
Why would "this" need to be anything but self-referential?
var s = new Sample { Title = "My Sample" };
//in this case, I want to see a string representation of "s"
Debug.WriteLine(s.ToString());
//in this case, we might want a copy
var s2 = (Sample)s.MemberwiseClone();
public class Sample
{
public string Title { get; set; }
public override string ToString()
{
//it wouldn't make sense to reference another object's "Title", would it?
return this.Title;
}
}
Is a "keyword" in C# used to refer the current instance of the class.
You can't assign a value to keyword, another example is keyword "base" and we can't assign a value. E.g. base = "text".
We can assign a value to an object through another class that contains the first.
public class TestClassParent
{
private TestClass _testObject;
public TestClassParent(TestClass testOject)
{
this._testObject = testObject;
}
}
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 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>();
}
}
}
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
I'm already aware that there are many other similar questions regarding this topic, however looking at the answers and adapting my code in relation to those has proved unsuccessful.
The code below is part of my Artist class, where I use CompareTo to compare between the artist name and the artist name (obj) passed in..
class Artists : IComparable
{
private string artistName;
private string artistMembers;
public int CompareTo(Object obj)
{
Artists otherArtist = (Artists)obj;
return artistName.CompareTo(otherArtist.ArtistName);
}
public Artists(string artist, string members){
ArtistName = artist;
Members = members;
}
public string ArtistName
{
set { artistName = value; }
get { return artistName; }
}
public string Members
{
set { artistMembers = value; }
get { return artistMembers; }
}
}
I really want to avoid making the variables public, which is a solution offered elsewhere, so I was wondering what I need to do to sort this problem out, and what I am doing wrong so I can learn from mistakes.
Thanks in advance.
EDIT 2
Closed VS and recompiled, and suddenly worked. Sorry for time wasting.
I'm assuming from your error that CompareTo is not public in your real code. Implicit interface implementations must be public.
You could implement the interface explicitly, and then clients would have to cast to IComparable to see the method:
int IComparable.CompareTo(Object obj) // will be private unless explicitly using the interface
{
Artists otherArtist = (Artists)obj;
return artistName.CompareTo(otherArtist.ArtistName);
}
Artists a1 = new Artists("Beatles", "Paul, Ringo");
Artists a2 = new Artists("U2", "Bono");
// this will fail:
//int i = a1.CompareTo(a2);
// this will work:
int i = ((IComparable)a1).CompareTo(a2);
However note that your class is internal by default, so the class is not even public.
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
}
}