Why am I getting a System.NullReferenceException error? [closed] - c#

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 create an alternative to the code found on this website (https://www.exercisescsharp.com/oop/first-class-method-tostring) where a dynamic list is used rather than an array. However, my code has failed to execute the ToString method and keeps giving me the NullReferenceException.
Below is my code:
public class MainClass
{
private static List<Person> person;
static void Main(string[] args)
{
string name = String.Empty;
while (name != null)
{
name = Console.ReadLine();
person.Add(new Person(name));
}
foreach (var individual in person)
{
Console.WriteLine(individual.ToString());
}
}
}
public class Person
{
private string name;
public Person (string _name)
{
name = _name;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string ToString()
{
return "Hello. My name is" + Name;
}
}

Your List instance is not initalized, you have to create it first.
private static List<Person> person = new List<Person>();

Related

JsonSerializer.Deserialize won't work in class C# [closed]

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 last year.
Improve this question
I am trying everything I can but the object is not getting deserialized, I tried almost all the possible solutions to the problem but nothing is working, if someone can help that would be great.
please see below is the code snippet for the code
it always returns a null value to me.
using System;
using System.Text.Json;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
var a = "{\"enrollmentType\":\"draft\",\"emrName\":\"accuro\",\"emrVersion\":\"v1\",\"workflowType\":\"coordinator\"}";
var x = "{\"enrollmentType\":\"draft\",\"emrName\":\"accuro\",\"emrVersion\":\"v1\",\"workflowType\":\"coordinator\"}";
string json = #"{""id"":10,""name"":""Name"",""revisionDate"":1390293827000}";
var ed = JsonSerializer.Deserialize<EnrollmentExtension>(x);
//.Replace("'", "\"")
if (!string.IsNullOrWhiteSpace(ed.emrName))
{ }
}
}
public class EnrollmentExtension
{
#region MyRegion
private string _emrName;
private string _emrVersion;
private string _workflowType;
private string _enrollmentType; public bool IsDraft()
{
return (string.Compare(_enrollmentType, "draft", true) == 0);
}
#endregion
public string enrollmentType
{
get { return _enrollmentType; }
private set { _enrollmentType = value; }
}
public string workflowType
{
get { return _workflowType; }
private set { _workflowType = value; }
}
public string emrVersion
{
get { return _emrVersion; }
private set { _emrVersion = value; }
}
public string emrName
{
get { return _emrName; }
private set { _emrName = value; }
}
public void SetWorkflowType(string workFlowType)
{
_workflowType = workFlowType;
}
}
public class Test
{
public EnrollmentExtension myprop { get; set; }
}
}
you have a bug in your classes, all your setters are private, but should be public. all properties should be like this
public string enrollmentType
{
get { return _enrollmentType; }
set { _enrollmentType = value; }
}
or you can keep the private setters but create a constructor
public EnrollmentExtension(string enrollmentType, ... and so on, string workflowType)
{
_enrollmentType=enrollmentType;
_workflowType=workflowType;
... and so on
}

" CS0122 'Collection<Larare>.Items' is inaccessible due to its protection level " but object is public [closed]

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
Im trying to use the Delete_Click funktion as laid out in https://stackoverflow.com/a/46898543/12955083
private void Delete_Click(object sender, EventArgs e){
lararLista.Items.Clear(); }
however I get error CS0122 'Collection.Items' is inaccessible due to its protection level
The collection Larare is defined in binding list as lararLista = new BindingList<Larare>();
and the code for Larare is
class Larare : Personal, ILarare
{
#region Variabler och ctor
private string namn;
private int personalID;
private long personNummer;
private long personNnummer;
private string email;
private int telNr;
public Larare(string Namn, int PersonalID, long PersonNummer, string Email, int TelNr)
{
this.Namn = namn;
this.PersonalID = personalID;
this.PersonNummer = personNnummer;
this.Email = email;
this.TelNr = telNr;
}
and the getter and setter are defined in a class that it inherits from
class Personal : IPersonal
{
private string namn;
private int personalID;
private long personNnummer;
private string email;
private int telNr;
private string taBort;
public string Namn
{
get { return namn; }
set { namn = value; }
}
public int PersonalID
{
get { return personalID; }
set { personalID = value; }
}
public long PersonNummer
{
get { return personNnummer; }
set { personNnummer = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public int TelNr
{
get { return telNr; }
set { telNr = value; }
}
public string TaBort
{
get { return taBort; }
set { taBort = value; }
}
where is the problem?
edit:
void lararLista_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Larare(personalNamnText.Text, int.Parse(personalPersonalIDText.Text), long.Parse(personalPersonnummerText.Text),
personalEmailText.Text, int.Parse(personalTelNrText.Text));
}
or lararLista.Add(new Larare("Rasmus", "123", "198911224130", "Rasmus#HS.se", "0704554488"));
is the code for adding new objects to the collection
The Items property in a BindingList is not public, so you can't access it directly. Try:
lararLista.ClearItems();

Most suitable way to access data [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 7 years ago.
Improve this question
Method 1:
public class1
{
private string _val1;
private string _val2;
public string Value1
{
get {return _val1;}
}
public string Value2
{
get {return _val2;}
}
public void ReadingDataFromDB()
{
//code to retrieve data from database
if(Reader.read())
{
_val1 = reader["val1"].ToString();
_val2 = reader["val2"].ToString();
}
}
}
Method 2:
public class1
{
public void ReadingDataFromDB(out string _val1, out string _val2)
{
_val1 = "";
_val2 = "";
//code to retrieve data from database
if(Reader.read())
{
_val1 = reader["val1"].ToString();
_val2 = reader["val2"].ToString();
}
}
}
In the Method 1 class has properties, but in Method 2 class has a method with output parameters. Both can be used to retrieve data from the database.
I have seen that often Method 1: is used for Business Logic and Method 2 is used for Data Access.
My question is, from the above Method 1 and Method 2 what is the better one for using in data access classes? And are there any specific reasons for that other than personal opinion?
I suggest something like that (Method 1 improved or Method 3):
public class MyClass {
//TODO: find better names for Value1, Value2
public String Value1 {get; private set}
public String Value2 {get; private set}
// static: the method actually creates an instance as read form DB
public static MyClass ReadFromDB() {
//TODO: Create a connection, SQL command here
if (Reader.Read()) {
return new MyClass() {
// Do not forget about NULL
Value1 = reader["val1"].IsDBNull ? null : Convert.ToString(reader["val1"]),
Value2 = reader["val2"].IsDBNull ? null : Convert.ToString(reader["val2"])
}
}
else
return null; // or throw an exception - no data in DB
}
}
...
MyClass test = MyClass.ReadFromDb();
Console.Write(test.Value1);
As for suggestions in the question: Method 2 ruins data incapsulation: it returns two strings when we expect corresponding properties (since we're working with class1); yet another problem is that out's are hard to read. As for Method 1, we usually expect that "ReadingDataFromDB" will read data from the database and return the intance (of class1) that's why I redesign the method into static and add return.
Take a look at an ORM, the EntityFramework for example.
However:
Basicly you should have a Model:
class FooModel {
public string Value1 {get;set;}
public string Value2 {get;set;}
}
And a Repository:
class FooRepository {
private _db;
public FooRepository(SqlConnection db) {
_db = db;
}
public FooModel GetFooModelById(int id) {
//...
var model = new FooModel {
Value1 = reader["val1"].ToString(),
Value2 = reader["val2"].ToString()
};
//...
}
public List<FooModel> GetFooModelCollection() {
//...
}
}
To bring it together:
var connection = new SqlConnection(...);
var repo = new FooRepository(connection);
var myFoo = repo.GetFooModelById(42);

No result in Console [closed]

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 8 years ago.
Improve this question
Why is the result of this empty and nothing shows up in the console?
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
pills sthnew= new pills("name", 25);
System.Console.WriteLine();
Console.ReadLine();
}
class pills
{
private int cena;
private string nazwa;
public int Price{
get { return price; }
set { price= value; }
}
public string Name
{
get { return name; }
set { name= value; }
}
public pills() { }
public pills(string Pname)
{
Pname = name;
}
public pills(string Pname, int Pprice)
{
Pname = name;
Pprice = price;
}
}
}
}
I am trying to write a class "Pills" which manages and keeps information about a current pill. The Class should have private fields: Name of Pill, Price of pill.
Because you are writing nothing in the console -
System.Console.WriteLine();
You need to write something to the console to see something on the console:
System.Console.WriteLine("something");

How to use protoBuf for struct serialization [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I want to serialize a class with protoBuf. My class has a field that is a struct. How can I serialize it?
[ProtoContract]
class P
{
[ProtoMember(1)]
private T t;
public P()
{ }
}
[ProtoContract]
public struct T
{
[ProtoMember(1)]
public int a;
[ProtoMember(2)]
public int b;
}
Just serialize/deserialize it - it should work fine. Because t is private, I added an accessor (that is only used by my code below - this accessor is completely unrelated to serialization):
public T T { get { return t; } set { t = value; } }
And then this works just fine:
static class Program
{
static void Main()
{
P p = new P { T = new T { a = 123, b = 456 } },
clone;
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, p);
ms.Position = 0;
clone = Serializer.Deserialize<P>(ms);
}
System.Console.WriteLine(clone.T.a); // 123
System.Console.WriteLine(clone.T.b); // 456
}
}

Categories