I am consuming a third party web service and I want to add value to match the service reference class, and i am not sure how to add value to the following:
in reference:
public partial class UserInfor: object, System.ComponentModel.INotifyPropertyChanged
{
private ABC[] listOfABCField;
public ABC[] ListOfABC
{
get {
return this.listOfABCField;
}
set {
this.listOfABCField = value;
this.RaisePropertyChanged("ListOfABC");
}
}
}
public partial class ABC : object, System.ComponentModel.INotifyPropertyChanged
{
private string ipField;
private string fristNameField;
private string lastNameField;
}
//////////////////////////////////////////////////////
in my service.asmx file have tried to put value as below:
in below code i got exception in line ABC[] abc=new ABC[0]; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC[] abc=new ABC[0];
abc[0].firstName= "petter";
abc[0].lastName = "lee";
user.ListOfABC = abc[1];
i also tried
in below code i got exception in line user.ListOfABC[0] = abc; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC abc=new ABC[0];
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC[0] = abc;
any idea how to add abc to user class ? thank you in advance
This'll probably be easier if you use a List<> instead of an array. Change the property:
private List<ABC> listOfABCField;
public List<ABC> ListOfABC
{
// etc.
}
Don't forget to initialize it in the class' constructor so it's not null:
public UserInfor()
{
listOfABCField = new List<ABC>();
}
Then you can just add an object to it, which doesn't need any of the array syntax you were trying to use:
UserInfor user = new UserInfor();
ABC abc = new ABC();
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC.Add(abc);
You are doing it wrong, first instantiate the array, if you know in advance how many items it would contain then specify that as well in the square brackets like:
ABC[] abc=new ABC[1]; // this array will contain 1 item maximum
now instantiate that item and then set values of properties :
abc[0] = new ABC(); // instantiating first item of array which is at 0th index
abc[0].firstName= "petter";
abc[0].lastName = "lee";
If you don't know how many item would come in it, then go with #David's suggestion of using List<T>
Related
using System;
public class Program
{
public static void Main()
{
CloudCollectionHelper cloudHelper = new CloudCollectionHelper();
SlackHelper slackHelper = new SlackHelper();
cloudHelper.DatabaseID=12345;
Console.WriteLine(slackHelper.GetSlackPageTokens());
}
class CloudCollectionHelper
{
public long DatabaseID { get; set; }
}
class SlackHelper:CloudCollectionHelper
{
public long GetSlackPageTokens()
{
return DatabaseID;
}
}
}
current output: 0
Expected Output: 12345
I need output 12345 because DatabaseID from the cloudhelper so i need that databaseID in the slackhelper.
this is my c# online compiler: https://dotnetfiddle.net/QNQeEX
The child class does not get the assigned values from the base class. Becouse there can be mutliple instances from it. For example, if you have
...
CloudCollectionHelper cloudHelper1 = new CloudCollectionHelper();
CloudCollectionHelper cloudHelper2 = new CloudCollectionHelper();
cloudHelper1.DatabaseID = 1234;
cloudHelper2.DatabaseID = 6789;
Console.WriteLine(slackHelper.GetSlackPageTokens()); //It would not know, what value to use.
...
The best way would be assigning the value directly to the child class or using the static modifier.
Edit:
Best way if you need to take this value from the child class for whatever reason would be doing something like this:
...
CloudCollectionHelper cloudHelper = new CloudCollectionHelper();
cloudHelper.DatabaseID = 12345; //First assign the needed Value
SlackHelper slackHelper = new SlackHelper(cloudHelper); //then create a new instance from the child class
...
and add the constructor from the SlackHelper child class like this:
class SlackHelper:CloudCollectionHelper
{
public SlackHelper(CloudCollectionHelper cloudHelper)
{
this.DatabaseID = cloudHelper.DatabaseID;
}
... //Do everything else what this class needs here
}
If the Value from cloudHelper.DatabaseID can update during the runtime, you will need a event to update the child class. It still isn't the best way to do this, because the DatabaseID value is already public and can be accessed without the child class.
Edit 2:
Like I already told you in the comments, you could also avoid this problem with the static modifier. But this will effect every instance made from the CloudCollectionHelper class. As soons as you make it static, this will only hold 1 possible value for all instances.
(Please keep in your mind to use a comment if needed or best case, just avoid Magic numbers)
The property of your Object slackhelper has not been affected.
You don't need to create a CloudCollectionHelper Object.
SlackHelper slackHelper = new SlackHelper();
slackHelper.DatabaseID=12345;
Console.WriteLine(slackHelper.GetSlackPageTokens());
You should create this property inside the class to allow to read the Database ID
public long GetSlackPageTokens()
{
return base.DatabaseID;
}
I've recently been looking into constructors, Im currently trying to pass a object to another class file, The way im doing it is like this:
class Program
{
static void Main(string[] args)
{
Class1 objPls = new Class1();
objPls.nameArray[0] = "jake";
objPls.nameArray[1] = "tom";
objPls.nameArray[2] = "mark";
objPls.nameArray[3] = "ryan";
Echodata form2 = new Echodata(objPls);
}
}
class Class1
{
public string[] nameArray = new string[3];
}
class Echodata
{
public Class1 newobject = new Class1();
public Echodata(Class1 temp)
{
this.newobject = temp;
}
// so now why cant i access newobject.namearray[0] for example?
}
Problem is i cant access the object to get into the array..
What methods of passing objects are there? I was told this is roughly a way to do it and have been experimenting for a while to no avail.
Not sure what it is you cannot do. For example your code with this modification works, or at least compiles.
class echodata
{
public Class1 newobject = new Class1();
public echodata(Class1 temp)
{
this.newobject = temp;
}
// so now why cant i access newobject.namearray[0] for example?
// What kind of access do you want?
public void method1()
{
newobject.nameArray[0] = "Jerry";
}
}
You have an issue where your code will throw an error when trying to set the "ryan" string on the fourth index of the array. You initially set the array to be of length 3.
In your EchoData class you can access the nameArray object without an issue but you must be accessing it within a method or in the constructor. You cannot be manipulating it's content outside of these.
Keep in mind that within your EchoData class you will not see the values you set inside of your Main method.
It's hard to tell since you haven't included a complete, compilable sample, and you haven't explained exactly what "can't access" means (do you get an error? what is it?)
However, my guess is that you are attempting to access the passed in objects fields from the class level based on your code.
ie, you are trying to do this:
class Echodata
{
public Class1 newobject; // you don't need to initialize this
public Echodata(Class1 temp)
{
this.newobject = temp;
}
newobject.newArray[0] = "Can't do this at the class level";
}
You can only access nameArray from within a member method.
class Echodata
{
public Class1 newobject; // you don't need to initialize this
public Echodata(Class1 temp)
{
this.newobject = temp;
}
public void DoSOmething() {
newobject.newArray[0] = "This works just fine";
}
}
I do a shop on a game and I want get a specifically array compared with the clicked button.
I have an object like this:
public class DressItem
{
private string text;
public string Text{
set{this.text = value;}
get{return this.text;}
}
private string mat;
public string Mat{
set{this.mat = value;}
get{return this.mat;}
}
}
Then in my script I create 3 DressItem item and I fill it with data, but I want one reference DressItem (named partRef) take property of one of previous array:
private DressItem[] pants;
private DressItem[] body;
private DressItem[] head;
private DressItem[] partRef;
How can I put object pants with this property in partRef and access to pants property like pant.text ?
I tried to put the 3 Dressitem in an arraylist and take it after like this:
private ArrayList arrayPart = new ArrayList();
arrayPart.Add(head);
arrayPart.Add(body);
arrayPart.Add(pants);
partRef = arrayPart(0) as DressItem;
But I have this error:
Cannot implicitly convert type 'DressItem' to `DressItem[]'
I tested to use a list but i must do a mistake i add my items like this:
private List<DressItem> arrayPart = new List<DressItem>();
arrayPart.Add(head);
arrayPart.Add(body);
arrayPart.Add(pants);
But i have this error :
The best overloaded method match for System.Collections.Generic.List.Add(DressItem)' has some invalid arguments.
I found my error: I typed my list as List<DressItem> instead of List<DressItem[]>, and the same for partRef. This was just a stupid mistake.
I am new to c# MVC and I don't understand my error:
Object reference not set to an instance of an object
I have the following in my Controller:
namespace Prigmore2013_01.Tests
{
public class Exercise09Controller : Controller
{
...
public ActionResult GuessTheDigits(List<int> guesses)
{
GuessingGame theGame = this.Session["GameState"] as GuessingGame;
theGame.GuessTheHiddenDigits(guesses);
// The above is passing to the method in GuessingGame class?
return RedirectToAction("Index", theGame);
}
...
}
}
I am calling the theGame.GuessTheHiddenDigits(guesses); and passing this across to the following class:
namespace Prigmore2013_01.Models
{
public class GuessingGame
{
public GuessingGame()
{
this.Guesses = new List<Guess>();
this.Target = new List<int>();
this.guess = new List<int>();
}
public List<int> Target { get; set; }
public List<Guess> Guesses { get; set; }
public List<int> guess { get; set; }
public void GuessTheHiddenDigits(List<int> guesses)
{
// getting the guesses passed from the controller, debugging shows that
this.guess = new List<int>(guesses);
Guess m = new Guess();
m.Digits.AddRange(this.guess);
}
}
}
I have another class called Guess:
namespace Prigmore2013_01.Models
{
public class Guess
{
public Guess()
{
this.Digits = new List<int>();
}
public List<int> Digits { get; set; }
public object RightDigitRightPosition { get; set; }
public object RightDigitWrongPosition { get; set; }
}
}
The above method public void GuessTheHiddenDigits(List<int> guesses) within here needs to add a submitted guess (guesses) to the List<Guess> objects. I thought I had instantiated the method by doing this:
this.guess = new List<int>(guesses);
Guess m = new Guess();
m.Digits.AddRange(this.guess);
EDIT 1:
Found the error that has formed within the Unit test that I am running:
[TestMethod]
public void GuessTheHiddenDigitsAddsTheSubmittedGuessToTheListOfGuesses()
{
var theGame = new GuessingGame();
/* NOTE : The next line forces us to add a behaviour to the GuessingGame
* class: the GuessTheHiddenDigits() method.
* */
theGame.GuessTheHiddenDigits(new List<int>() { 1, 2, 3 });
var theContext = new FakeHttpContext();
var theKey = "GameState";
theContext.Session.Add(theKey, theGame);
var controller = new Exercise09Controller();
var request = new System.Web.Routing.RequestContext(theContext, new System.Web.Routing.RouteData());
controller.ControllerContext = new System.Web.Mvc.ControllerContext(request, controller);
//Finally, set up the new guess
var theGuess = new List<int>() { 2, 3, 4 };
//Act
controller.GuessTheDigits(theGuess);
var result = controller.ShowPreviousGuesses();
var lastGuess = ((List<Guess>)result.Model).LastOrDefault();
//Assert
/* NOTE : This line forces another implementation decision: to use a
* C# property for Guess.Digits to represent the player's guess.
* */
CollectionAssert.AreEqual(theGuess, lastGuess.Digits);
}
My Unit test breaks on the lastGuess.Digits as this is null. Does this mean I require a constructor initially to create a new list so that isn't null and will not throw the error?
I seem to be going round in circles and don't quite understand what is causing this to not be set. Would it be possible for someone to explain to me why my method isn't adding to my List<Guess> and the best approach for adding my submitted guess to List<Guess>?
Object reference not set to an instance of an object
means that you're using a variable which equals to null, I guess that following lines are problematic:
GuessingGame theGame = this.Session["GameState"] as GuessingGame;
theGame.GuessTheHiddenDigits(guesses);
So in this case theGame is probably not set, because you haven't saved it in Session["GameState"], thus it throws an error because you're trying to call a method on nulled variable.
UPDATE
Since you already know where this error occurs, then you need to know that using a variable which has a null value will result in this kind of error, to prevent it you need to initialize your variables.
First off, use the debugger and when you get that error inspect your objects/properties to see which one is null.
I seem to be going round in circles and don't quite understand what is
causing this to not be set. Would it be possible for someone to
explain to me why my method isn't adding to my List and the
best approach for adding my submitted guess to List?
In GuessingGame.GuessTheHiddenDigits method you are creating a local scope object of type Guess, and adding the passed in List<int> to that ... nowhere are you actually adding anything to your GuessingGame.Guesses list. That 'm' will be removed as soon as that method has finished executing.
Are you then intending to add 'm' to your List?
Like:
Guess m = new Guess();
m.Digits.AddRange(this.guess);
this.guess.Add(m);
Oh, and this.guess doesn't match naming rules for public properties ... call it this.Guess instead.
I have created a list within a class, following the same sort of lines as
public class Data
{
private int num;
private string text;
public Data()
{
}
public int Num
{
get { return num; }
set { num = value; }
}
public string Text
{
get { return text; }
set { text = value; }
}
static private List<Data> DataList = new List<Data>();
static public List<Data> GetList()
{
return DataList
}
and I bring up the list in other classes using
List<Data> DataList = Data.GetList();
does getting the list in another class allow you to add items to it?
and how would I add the items to a combobox?
EDIT: i am trying
LstList.Items.Add(DataList.Any(item => item.Num));
but I get the errors "cannot implicitly convert type int to bool"
and "A local variable named "Data" cannot be declared in this scope because it would give a different meaning to "Data""
EDIT: I have tried using .DataSource, but apparently it doesn't exist?
If I understand correctly, you are looking at adding new items to the static List in the above code from some other Class. If so, then no you cant do it. If you want to do it, expose a method called
public static void SetList(Data item_)
{
DataList.Add(item_);
}
Or make the List Public to be exposed to other classes
To your second point one assigns the data source of the comboBox to the List.
comboBox.DataSource= DataList;
This is an additional link that would help
How do I do bind list of custom objects to ComboBox?
You can bind the list as a DataSource
comboboxName.DataSource = Data.GetList();
comboboxName.ValueMember = "Num";
comboboxName.DisplayMember = "Text";
loop each data class from DataList and add the num property to the ListView Control
foreach(Data aData in DataList)
{
LstList.Items.Add(aData.Num.ToString()));
}