i have some mandatory fields and when calling the constructor of my class i got null reference exception, how prevent this please.
new Part(Partitems["Name"].ToString(), Partitems["Logo"].ToString(), Partitems["Description"].ToString(), Partitems["URL"].ToString()));
MY Class :
public class Part
{
string _Name= string.Empty;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
…
..
EDIT
Here is constructor code
public Part(string Name, string Logo, string Description, string URL)
{
this.Name = Name;
this.Logo = Logo;
this.Description = Description;
this.URL = URL;
}
There’s nothing in the constructor that could cause a null reference exception, as assigning null to a string property is perfectly valid. So, either your
Partitemsvariable is null, or one of it’s properties returns null.Example for handling both situations:
This will replace any null values in the properties with empty strings. However, you might want to handle it as an error situation instead, depending on the situation.