Tag: c# relation between properties and fields

A problem about the AUTO-implemented properties and the MANUALLY implemented properties

I have to mark this down beacause I lately made a stupid error.  In a little task, I have to inherit some properties in the parent class. I wrote this way:

class Parent
{
private int numéroDeSérie;
private string nomDuNavire;
private int nombreDeMatelots;

public int NuméroDeSérie {get; set;}
public string NomDuNavire {get; set;}
public int NombreDeMatelots {get; set;}
}

When I had to access the properties(NuméroDeSérie,NomDuNavire,NombreDeMatelots) of the Parent class from the inherited Child class, they contained only value null. I found out afterwards that the problem was that the private fields showed no relation to the properties at all. All my action over the privated fields would not be appled to properties, vice versa.

If I have to use the private fields in the parent, I can use the auto-implemented properties as follows:

class Naivre
{
private int numéroDeSérie;
private string nomDuNavire;
private int nombreDeMatelots;

public int NuméroDeSérie
{
get
{
return numéroDeSérie;
}

set
{
numéroDeSérie = value;
}
}

public string NomDuNavire
{
get
{
return nomDuNavire;
}

set
{
nomDuNavire = value;
}
}

public int NombreDeMatelots
{
get
{
return nombreDeMatelots;
}

set
{
nombreDeMatelots = value;
}
}

Otherwise, I should do my action on the public properties themselves in the Parent class and remove the private fields which I thought having a relation to the properties but not in reality.

Advertisements