NullReferenceException and I Don't Know Why - c#

I have two classes:
class Player
{
public string Id { set; get; }
public int yPos { set; get; }
public List<Shot> shots;
public Player(string _Id, int _yPos)
{
Id = _Id;
yPos = _yPos;
}
}
class Shot
{
public int yPos { set; get; }
public Shot(int _yPos)
{
yPos = _yPos;
}
}
When I try to put new Shot in list of shots for the player I get NullReferenceException:
Player pl = new Player("Nick",50);
pl.shots.Add(new Shot(pl.yPos)); // this line throws exception
Probably something ultimately simple.

In your Player constructor, just initialize shots = new List<Shot>();

You need to new the shots in the Player constructor (or before you add to it).
shots = new List<Shot>();

I like the below a bit better, only initialize shots if you need it and if you ever need to add logic to accessing Shots, you can without having to alter the use of Shots all over the place.
private List<Shot> _shots;
public List<Shot> Shots
{
get
{
if (_shots == null)
{
_shots = new List<Shot>();
}
return _shots;
}
set
{
_shots = value;
}
}

Related

How to create a structure with embedded fields?

I am looking for information about that in the internet but with no success. The goal is to realize a sort of dataset of 10 subject (sub_1, sub_2... sub_10), each of them has done 3 kind of activities (walk, run, jump) for three time each (trial_1... trial_3) with relative scores. I would like to access these information like:
variable = dataset.sub_1.jump.trial_2.score;
or, at least:
variable = dataset.sub[0].task[2].trial[1].score;
So, the structure would be a tree structure. Until now I only realized a structure with "parallel fields":
struct dataset
{
public string[] sub; // 1 to 10 subjects
public string[] task; // 1 to 3 tasks
public string[] trial; // 1 to 3 trials
public int score; // the score of the above combination
}
Any idea?
This problem can be solved in many ways.
My solution has one drawback, there is no check if user exceeded Score arrays capacity.
I guess database tag has nothing to do with this question
using System;
using System.Linq;
namespace ConsoleApp
{
public abstract class Task
{
public string Name { get; set; }
public int TotalScore { get { return Score.Sum(); } }
public int[] Score { get; set; } = new int[3];
}
public class Walk : Task { }
public class Run : Task { }
public class Jump : Task { }
public class Subject
{
public Walk Walk { get; set; } = new();
public Run Run { get; set; } = new();
public Jump Jump { get; set; } = new();
public int TotalScore { get { return Walk.TotalScore + Run.TotalScore + Jump.TotalScore; }}
}
class Program
{
static void Main(string[] args)
{
var subject = new Subject();
// Adding score to specific trials
subject.Run.Score[0] = 50;
subject.Run.Score[1] = 40;
subject.Run.Score[2] = 60;
subject.Jump.Score[0] = 40;
subject.Jump.Score[1] = 80;
subject.Jump.Score[2] = 100;
// Output score of 1. trial for Walk task
Console.WriteLine(subject.Walk.Score[0]);
// Output total score as a sum of all trials for Jump task
Console.WriteLine(subject.Jump.TotalScore);
// Output total score as a sum of all trials in all tasks
Console.WriteLine(subject.TotalScore);
// ERROR CASE: this will be exception
subject.Jump.Score[3] = 100;
}
}
}
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
public class Trial
{
public Trial(int score)
{
Score = score;
}
public int Score { get; set; }
}
public class Task
{
public List<Trial> Trials { get; } = new List<Trial>();
}
public class Subject
{
public Dictionary<string, Task> Tasks { get; } = new Dictionary<string, Task>();
public Subject()
{
Tasks.Add("walk", new Task());
Tasks.Add("run", new Task());
Tasks.Add("jump", new Task());
}
}
class Program
{
static void Main(string[] args)
{
Subject player1 = new Subject();
player1.Tasks["run"].Trials.Add(new Trial(score: 3));
Console.WriteLine(player1.Tasks["run"].Trials[0].Score);
}
}
}
Maybe a class for everything is too much, but maybe you want to add a description property for tasks one day or a timestamp for the trial. Then it's ok.
public class Subject
{
private Dictionary<string,Activity> _activities { get; }= new Dictionary<string, Activity>();
public Activity this[string activity]
{
get
{
if (!_activities.Keys.Contains(activity))
_activities[activity] = new Activity();
return _activities[activity];
}
set
{
_activities[activity] = value;
}
}
public int Score => _activities.Values.Sum(x => x.Score);
}
public class Activity
{
private Dictionary<int, Trial> _trials { get; } = new Dictionary<int, Trial>();
public Trial this[int trial]
{
get
{
if (!_trials.Keys.Contains(trial))
_trials[trial] = new Trial();
return _trials[trial];
}
set
{
_trials[trial] = value;
}
}
public int Score => _trials.Values.Sum(x => x.Score);
}
public class Trial
{
public int Score { get; set; }
}
public class Answer
{
public void DoSomething()
{
Subject Mindy = new Subject();
Mindy["curling"][1].Score = 5;
Mindy["bowling"][1].Score = 290;
Console.WriteLine(Mindy.Score);
}
}
This is what I would guess you think you need... but from your question I think you're still new to C# and might want to rethink your concept. It looks like a very database-oriented way of looking at the problem, so maybe you might want to take a look at dapper to more closely match your database.
Also, avoid using the classname Task, this can imo only cause confusion if you ever start using multithreading (System.Threading.Task is a .NET framework component)

Why am I getting this error while making a asp.net web api?

Controller.cs
[HttpGet]
public async Task<ActionResult<IEnumerable<RankDistribution>>> GetTodoItems()
{
List<rank> rklist = new List<rank>();
rank rk = new rank
{
rankID = 0,
rankName = "Plastic 1",
playersInRank = 1,
percentInRank = 100f
};
rklist.Add(rk);
var rb = new RankDistribution
{
Id = 0,
rank = rklist
};
return rb;
}
Class.cs
public class RankDistribution
{
public long Id { get; set; }
public List<rank> rank { get; set; }
}
public class rank
{
public string rankName { get; set; }
public int rankID { get; set; }
public int playersInRank { get; set; }
public float percentInRank { get; set; }
}
Error Message
Cannot implicitly convert type 'RankAPI.Models.RankDistribution' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<RankAPI.Models.RankDistribution>>
I have only recently started working on an api, but I am pretty familiar on C#. How do I convert the return value so it goes through? Thanks!
You are returning a single item of RankDistribution
You should include it in a List and return the list
var toRet = new List<RankDistribution>();
toRet.Add(rb);
return toRet;
But in my opinion if you have the RankDistribution that contains a list inside of the items you want to return why not returning just rb and change the syntax of your method to
ActionResult<RankDistribution>

C# How to make an object from class Person kill another?

In the following code, I'm trying to learn how to get objects to interact with each other, because I feel that's a bit more important than what I have done now which is simply collect a bunch of variables assign to each object.
For fun, what I want these different objects to do is to kill each other. The person named Jack can kill. The other two can not. What I want Jack to do is strike the other two, making them lose 1, 5 or 10 HitPoints multiple times until they are dead, and then set their Alive to false.
I don't know how to even start this, but I think it would be a very fun and interesting exercise.
The most important thing about doing this is learning how one object can directly change something about a different object, just because it can, and that the objects it has then changed, will then suffer a consequence from this action.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP_Learning
{
class Program
{
static void Main(string[] args)
{
Person p1;
p1 = new Person("Jack", 27, true, true, 10);
Person p2;
p2 = new Person("Vincent", 63, true, false, 10);
Person p3;
p3 = new Person("Tim", 13, true, false, 10);
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool Alive { get; set; }
public bool AbilityToKill { get; set; }
public int HitPoints { get; set; }
public Person(string name, int age, bool alive, bool abilityToKill, int hitPoints)
{
HitPoints = hitPoints;
AbilityToKill = abilityToKill;
Alive = alive;
Name = name;
Age = age;
}
}
}
You need 2 methods in the Person class.
Hit -> This method reduce the HitPoints on self object with each hit. When the HitPoints become Zero, status Alive is set to false.
Kill -> This will take person as a parameter and call Hit method on that person till that person is Alive.
Add following methods to Person class:
public void Hit()
{
if(Alive)
{
if(HitPoints > 0)
{
HitPoints -= 1;
}
else
{
Alive = false;
}
}
}
public bool Kill(Person person)
{
if(!AbilityToKill)
{
Console.WriteLine("You don't have ability to kill! You cannont kill {0}.", person.Name);
return false;
}
while(person.Alive)
{
person.Hit();
}
Console.WriteLine("{0} is dead.", person.Name);
return true;
}
Call Kill method in Main method.
p2.Kill(p3);
p1.Kill(p2);
p1.Kill(p3);
Hope this helps!
Is this the kind of thing you mean?
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public bool Alive { get; private set; }
public bool AbilityToKill { get; private set; }
public int HitPoints { get; private set; }
public void Hit(int points)
{
this.HitPoints -= points;
if (this.HitPoints <= 0)
{
this.HitPoints = 0;
this.Alive = false;
}
}
public Person(string name, int age, bool alive, bool abilityToKill, int hitPoints)
{
this.HitPoints = hitPoints;
this.AbilityToKill = abilityToKill;
this.Alive = alive;
this.Name = name;
this.Age = age;
}
}
Now with the check for AbilityToKill:
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public bool Alive { get; private set; }
public bool AbilityToKill { get; private set; }
public int HitPoints { get; private set; }
public int Attack(Person victim, int points)
{
var hp = victim.HitPoints;
if (this.AbilityToKill)
{
victim.HitPoints -= points;
if (victim.HitPoints <= 0)
{
victim.HitPoints = 0;
victim.Alive = false;
}
}
hp -= victim.HitPoints;
return hp;
}
public Person(string name, int age, bool alive, bool abilityToKill, int hitPoints)
{
this.HitPoints = hitPoints;
this.AbilityToKill = abilityToKill;
this.Alive = alive;
this.Name = name;
this.Age = age;
}
}
This can be used like this:
var jack = new Person("Jack", 27, true, true, 10);
var vincent = new Person("Vincent", 63, true, false, 10);
var tim = new Person("Tim", 13, true, false, 10);
var damage_done = jack.Attack(vincent, 20);
Console.WriteLine(damage_done);
The Attack method returns the actual number of hits points reduced by the attack - the damage dealt.
And here's a more strongly-typed version. Using bool for properties isn't always the clearest way to code. Through in some enums and it's clearer.
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public Alive Alive { get; private set; }
public AbilityToKill AbilityToKill { get; private set; }
public int HitPoints { get; private set; }
public int Attack(Person victim, int points)
{
var hp = victim.HitPoints;
if (this.AbilityToKill == AbilityToKill.Yes)
{
victim.HitPoints -= points;
if (victim.HitPoints <= 0)
{
victim.HitPoints = 0;
victim.Alive = Alive.No;
}
}
hp -= victim.HitPoints;
return hp;
}
public Person(string name, int age, Alive alive, AbilityToKill abilityToKill, int hitPoints)
{
this.HitPoints = hitPoints;
this.AbilityToKill = abilityToKill;
this.Alive = alive;
this.Name = name;
this.Age = age;
}
}
public enum Alive { Yes, No }
public enum AbilityToKill { Yes, No }
It's used like this:
var jack = new Person("Jack", 27, Alive.Yes, AbilityToKill.Yes, 10);
var vincent = new Person("Vincent", 63, Alive.Yes, AbilityToKill.No, 10);
var tim = new Person("Tim", 13, Alive.Yes, AbilityToKill.No, 10);
var damage_done = jack.Attack(vincent, 20);
Console.WriteLine(damage_done);

Form sending data to another form

I'm currently trying to make a form that sends 2 class, then receives the data, uses them but want to shoot them back to the original form. Any idea on how I could?
This is when i call my second form:
var tmp = new Pjeu(P1,P2);
tmp.Show();
P are Players. Here's the class:
//---
public class Player
{
public string Name;
public int pts1;
public int pts2;
public int num;
};
And I receive the data like this:
label3.Text = P1.Name;
label5.Text=P2.Name;
I want to use P1.pts or shoot back a number to it. Is it possible the way I do?
You can use multi way:
public class Player
{
public void Pa(string p1,string p2)
{
p1 = Name;
p2 = Name;
}
public string pass1(int ps1)
{
return ps1.ToString();
}
public string pass2(int ps2)
{
return ps2.ToString();
}
public string Name { get; set; }
public int pts1 { get; set; }
public int pts2 { get; set; }
public int num { get; set; }
}
and call:
Player p = new Player();
p.Pa(Label1.Text, Label2.Text);
Label1.Text = p.pts1.ToString();
Label2.Text = p.pts2.ToString();

Object within an object is null

I'm using C# and have created an object to send to a JSON service that looks like this:
public class SendRequest
{
public string id { get; set; }
public string case { get; set; }
public string method { get; set; }
public Volume value { get; set; }
}
public class Volume
{
public int level;
public bool mute;
}
I can code hint when setting the sub object:
var _req = new SendRequest();
_req.value.mute = false;
_req.value.level = 50;
But when the program is run, the sub-object itself is null (_req.value = null) and the two items under that object don't show.
Why is this happening?
You need to initialize the "value" to something.
Add this constructor to your SendRequest class:
public SendRequest(){ value = new Volume(); }
You can use object initializers
var _req = new SendRequest()
{
value = new Volume()
{
mute = false,
level = 50,
},
};
at this point method is null
public string method { get; set; }
longer but what you can do is
private string method = string.empty;
public string Method { get {return method;} set {method = value;} }
value is just a bad name
private Volume volume = new Volume();
public Volume Volume { get {return volume;} set {volume = value;} }
or
volume = new Volume (mute = false, value.level = 50);

Categories

Resources